<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\bpm\XHBpmPlan;
use Admin\Models\bpm\XHBpmTransList;
use Admin\Models\crm\XhcustInfo;
use Admin\Models\device\XhdeviceBoxInfo;
use Admin\Models\device\XhsysDevicecheck;
use Admin\Models\device\XhsysDevicerepairDelay;
use Admin\Models\device\XhsysDevicerepairhandle;
use Admin\Models\device\XhsysDevicerepairProject;
use Admin\Models\device\XhsysDeviceSignIn;
use Admin\Models\hrm\XhhrmResource;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsBrand;
use Admin\Models\ims\XHImsProdIn;
use Admin\Models\ims\XHImsProdOut;
use Admin\Models\ims\XHImsProdType;
use Admin\Models\ims\XHImsProduce;
use Admin\Models\ims\XHImsProduceIn;
use Admin\Models\ims\XHImsProduceOut;
use Admin\Models\ims\XHImsProduceType;
use Admin\Models\ims\XHImsReturnTab;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\user\XhsysUserstud;
use Admin\Models\log\LoginLog;
use Endroid\QrCode\QrCode;
use Helpers\Device;
use Helpers\Main;
use Helpers\Hrm;
use Helpers\Assets;
use Helpers\phpmailerException;
use Helpers\Queue;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\HttpClient;
use Helpers\XhException;
use Hrm\Models\XHHrmAttendence;
use Modules\Customer;
use Modules\Ims;
use Modules\Power;
use Modules\ProcessPlan;
use Modules\School;
use Admin\Models\user\XhsysUser;
use Admin\Models\device\XhsysUsertablet;
use Admin\Models\device\XhsysTabletExchange;
use Admin\Models\device\XhsysUsertabletNote;
use Admin\Models\device\XhsysAccountdevicelocked;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\device\XhsysDevicerepair;
use Admin\Ims\Models\XHImsProduct;
use Modules\Coop;
use Helpers\Area;
use Services\Box;
use Phalcon\Mvc\View;

class DeviceController extends ControllerBase
{

    private $registerEnum = [
        'iReceivePurpose'   => [
            0 => '<div class="grid-cell-text-bg-green">自用</div>',
            1 => '<div class="grid-cell-text-bg-blue">备用</div>',
            2 => '<div class="grid-cell-text-bg-yellow">学校公用</div>',
            3 => '<div class="grid-cell-text-bg-gray">教师机</div>'
        ],
        'iCheck'            => [0 => '未备注', 1 => '待审核', 2 => '已审核'],
        'iSource'           => [0 => '自动', 1 => '手动', 2 => '变更'],
        'bDone'             => [0 => '使用中', 1 => '使用完毕'],
        'iReceiveStatus'    => [1 => '待领用', 2 => '已领用', 3 => '已归还'],
        'iBuyType'          => [1 => '正常', 2 => '校购', 3 => '自购'],
        'bDemo'             => [0 => '否', 1 => '是'],
        'bDelete' => ['bDelete' => [0 => '<i class="fa fa-check"></i>', 1 => '<i class="fa fa-history"></i>']],
        'destination'       => ['1' => '公司', '2' => '维修站'],
        'checkResult'       => ['1' => '免费', '2' => '收费', '3' => '无法检修'],
        'agreeCharge'       => ['1' => '不同意', '2' => '同意'],
        'renewal'           => ['0' => '否', '1' => '是'],
        'iConfirmCharge'    => ['0' => '否', '1' => '是'],
        'iCreateType'       => ['1' => '学生', '2' => '领用', '3' => '创建'],
        'progress'          => [
            0 => '未开始', 1 => '已接收', 2 => '送修中', 3 => '在检测', 4 => '无法维修待寄回', 5 => '收费沟通中', 6 => '不同意收费待寄回',
            13 => '收费确认中', 16 => '待维修', 7  => '维修中', 8  => '维修完成', 9  => '寄回中', 12 => '返回重修',
            15 => '已领取', 10 => '正常开机', 11 => '未维修'
        ],
        'repairPurposeType' => [1 => '学生机', 2 => '自用', 3 => '备用', 4 => '学校公用', 5 => '教师机', 6 => '库存'],
        'commType'          => [1 => '同意收费沟通', 2 => '不同意收费沟通', 3 => '正常沟通']
    ];

    private $checkDelayStatus = [2, 4, 5, 6, 7, 8, 18, 13, 9];
    private $delayStatus = [1 => '检测', 2 => '收费沟通', 3 => '收费确认', 4 => '维修'];
    private $delayRepairStatus = [1 => [3], 2 => [5], 3 => [13], 4 => [16, 7]];
    private $boxStatus = [1 => '在线', 2 => '断开'];
    private $boxType = [1 => '文件盒子', 2 => '课堂盒子', 3 => '其他'];
    private $schoolType = [0 => '意向学校', 1 => '合作学校', 2 => '前期接触', 3 => '终止合作',];
    private $deviceSignIn = [0 => '未签收', 1 => '已签收'];
    private $openStatus = [0 => '关', 1 => '开'];


    /**
     * 领用列表页面
     *
     * create by ck 20170619
     * modify by ck 20180823    型号更改为下拉框
     */
    public function registerListAction()
    {
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('device/registerList');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/device/registerList.js');
        $mine = !!$this->request->getQuery('mine', 'int', 0);
        if (!UserPower::checkUserPower($mine ? 'Device_MineRegister' : 'Device_registerList')){
            return $this->sendViewError('无查看此页面权限');
        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_purpose', 'style' => 'width:80px;', 'data' => ['' => '--用途--'] + $this->registerEnum['iReceivePurpose']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_status', 'style' => 'width:100px;', 'data' => ['' => '--领用状态--'] + $this->registerEnum['iReceiveStatus']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_done', 'style' => 'width:100px;', 'data' => ['' => '--使用状态--'] + $this->registerEnum['bDone']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_check', 'style' => 'width:100px;', 'data' => ['' => '--审核状态--'] + $this->registerEnum['iCheck']];
        if (!$mine) {
            $listSearchArr[] = ['type' => 'select', 'id' => 'list_item', 'multiple' => 'true', 'style' => 'width:110px;', 'data' => [
                ''                      => '默认',
                'sDevNumber'            => '设备号',
                'sDevType'              => '设备型号',
                'sMacAddress'           => 'MAC地址',
                'sReceiverName'         => '领用人',
                'sReceiverAccount'      => '领用账号',
                'sReceiverPhone'        => '领用手机',
                'sNowReceiverName'      => '当前领用人',
                'sNowReceiverAccount'   => '当前领用账号',
                'sRealUserName'         => '使用人',
                'sRealUserAccount'      => '使用账号',
                'tLastModifyDate'       => '最后修改时间',
            ]];
        }
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_school', 'style' => 'width:100px;', 'label' => ' 学校: '];
//        $listButtonArr[] = ['id' => 'bt_list_group', 'class' => 'menubutton', 'text' => '分组查看', 'plain' => 'true', 'icon' => 'fa-group'];
        if (UserPower::checkUserPower('Device_registerList_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '添加', 'plain' => 'true', 'icon' => 'fa-plus'];
        }
        if (UserPower::checkUserPower('Device_registerList_Done')) {
            $listButtonArr[] = ['id' => 'bt_list_done', 'text' => '归还', 'plain' => 'true', 'icon' => 'fa-check'];
            $listButtonArr[] = ['id' => 'bt_list_start_receive', 'text' => '领用', 'plain' => 'true', 'icon' => 'fa-tablet'];
        }
        if (UserPower::checkUserPower('Device_MineRegister_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_change_school', 'text' => '更改学校', 'plain' => 'true', 'icon' => 'fa-pencil'];
        }
        if (UserPower::checkUserPower('Device_registerList_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        if (UserPower::checkUserPower('Device_registerList_Syn')) {
            $listButtonArr[] = ['id' => 'bt_list_syn', 'text' => '同步数据', 'plain' => 'true', 'icon' => 'fa-refresh'];
        }
        if (UserPower::checkUserPower($mine ? 'Device_MineRegister_Repair' : 'Device_registerList_Repair')) {
            $listButtonArr[] = ['id' => 'bt_list_repair', 'text' => '设备维修', 'plain' => 'true', 'icon' => 'fa-wrench'];
        }
        if (Power::exist('Device_ReturnTab_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_returnTab',  'text' => '退还申请', 'plain' => 'true', 'icon' => 'fa-tablet'];
        }
        if (Power::exist('LicenceDevList_Bind')) {//来源--运营管理--学生管理--学生列表
            $listButtonArr[] = ['id' => 'bt_list_bindLicence', 'text' => '绑定许可证', 'plain' => 'true', 'icon' => 'fa-link'];
        }
        $listButtonArr[] = ['id' => 'bt_list_history', 'text' => '查看历史', 'plain' => 'true', 'icon' => 'fa-history'];
        $power = ['note' => false, 'isAdmin' => User::isAdmin() ? 1 : 2];
        if (Power::exist('Device_registerList_Note')) {//备注
            $power['note'] = true;
        }
        $listButtonArr[] = ['id' => 'bt_list_communication', 'class' => 'menubutton', 'text' => '备注', 'plain' => 'true', 'icon' => 'fa-commenting-o'];
        if (Power::exist('Device_Exchange_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_exchange', 'text' => '设备变更', 'plain' => 'true', 'icon' => 'fa-exchange'];
        }
        $this->registerEnum['iSchoolId'] = ['' => '--选择--'] + XhschoolInfo::getSchoolSupportArray();
        $devType = Ims::getProdsByTypeName('平板', true);
        $devType = array_combine($devType, $devType);
//        $devType = array_column($devType, 'sProdName', 'sProdName');
        $this->registerEnum['sDevType'] = $devType;
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHSys_UserTablet', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'          => Template::createForm('Device_Register', $this->registerEnum),
            'FormButton'    => Template::createButtonToolBar(Main::createFormButton('Device_registerList')),
            'power' => $power
        ]);
    }

    /**
     * 获取领用设备列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170619
     * modify by ck 20170630    添加设备型号筛选
     * modify by ck 20170920    结构更改，可根据目的修改
     * modify by ck 20171207    根据设备号展示
     * modify by ck 20171219    更改计算方式
     * modify by ck 20180223    我的领用添加学校权限
     * modify by dale 20180713  代理商平板领用
     * modify by ck 20180828    重构
     */
    public function getRegisterAction()
    {
        $purpose = $this->request->getPost('purpose', 'int');
        $done    = $this->request->getPost('done', 'int');
        $status  = $this->request->getPost('status', 'int');
        $school  = $this->request->getPost('school', 'string');
        $mine    = !!$this->request->getPost('mine', 'int', 0);
        $schoolId = $this->request->getPost('schoolId', 'string');
        $iCIId = $this->request->getPost('iCIId', 'int');
        $addLogin    = $this->request->getPost('addLogin','string');//是否添加登录信息
        $check  = $this->request->getPost('check', 'int');
        $params = [
            'conditions' => 'bDelete = 0 AND bHistory = 0',
            'order'      => 'iUTId desc'
        ];
        if ($iCIId) {
            $staffIds = $this->db->fetchAll("select iStaffId from XHCoop_Contact WHERE bDelete = 0 and iStaffId is not null and iCIId = {$iCIId} ");
            $staffIds = array_values(array_filter(array_column($staffIds,'iStaffId')));
            if (count($staffIds) > 0) {
                $params['conditions'] .= ' AND iStaffId in ({staffIds:array})';
                $params['bind']['staffIds'] = $staffIds;
            } else {
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
        }
        if ($purpose != '') {
            $params['conditions'] .= ' AND iReceivePurpose = :purpose:';
            $params['bind']['purpose'] = $purpose;
        }
        if ($done != '') {
            $params['conditions'] .= ' AND bDone = :done:';
            $params['bind']['done'] = $done;
        }
        if ($check !== '' && $check !== null) {
            $params['conditions'] .= ' AND iCheck = :iCheck:';
            $params['bind']['iCheck'] = $check;
        }
        if ($status) {
            $params['conditions'] .= ' AND iReceiveStatus = :status:';
            $params['bind']['status'] = $status;
        }
        else {
            $params['conditions'] .= ' AND iReceiveStatus <> 3';
        }
        if ($school) {
            $schoolIds = School::searchSchool($school);
            if (!$schoolIds) {
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
            }
            $params['conditions'] .= ' AND iSchoolId in ({schoolIds:array})';
            $params['bind']['schoolIds'] = $schoolIds;
        }
        if ($schoolId) {
            $params['conditions'] .= ' AND iSchoolId = :schoolId:';
            $params['bind']['schoolId'] = $schoolId;
        }
        if ($mine) {
            $phoneNum = XhhrmStaff::findFirst([
                'conditions' => 'bDelete = 0 AND iUserId = :userId:',
                'columns'    => 'sSelfPhone',
                'bind'       => ['userId' => User::getId()]
            ])->sSelfPhone;
            if (!$phoneNum) {
                return $this->sendDataGridError('非员工无法查询');
            }
            $schoolPowerIds = School::getPower();
            if (!$schoolPowerIds) {
                $params['conditions'] .= ' AND sReceiverPhone = :phoneNum:';
                $params['bind']['phoneNum'] = $phoneNum;
            }
            else if ($schoolPowerIds !== true) {
                $params['conditions'] .= ' AND (sReceiverPhone = :phoneNum: OR iSchoolId in ({schoolPowerIds:array}) OR iNewSchoolId in ({iNewSchoolId:array}))';
                $params['bind']['phoneNum'] = $phoneNum;
                $params['bind']['schoolPowerIds'] = $schoolPowerIds;
                $params['bind']['iNewSchoolId'] = $schoolPowerIds;
            }
//            else {
//                $params['conditions'] .= ' AND (sReceiverPhone = :phoneNum: OR 1)';
//                $params['bind']['phoneNum'] = $phoneNum;
//            }
        }
        $enum = $this->registerEnum;
        $enum['iNewPurpose'] = $enum['iReceivePurpose'];
        Main::runSearchVagueConditions($params['conditions'], ['sDevNumber', 'sDevType', 'sMacAddress', 'sReceiverName', 'sReceiverAccount', 'sReceiverPhone', 'sNowReceiverName', 'sNowReceiverAccount']);
        $data = Main::runModelPage('\\Admin\\Models\\device\\XhsysUsertablet', $params, $enum);
        if ($addLogin == 'true') {
            $this->addLastLogInInfo($data['rows']);
            $changeArr['logInName'] = 'logInName';
        }
        $changeArr['iLastModifyUserId'] = 'iLastModifyUserId';
        Main::runUserName($data['rows'], $changeArr);
        School::runName($data['rows'], ['iSchoolId' => 'sSchoolName']);
        foreach ($data['rows'] as &$value) {
            if ($value['iBeforeUTId']) {//加上记录的前身数据
                $beforeData = XhsysUsertablet::findFirst(['conditions' => 'iUTId = :iUTId:', 'bind' => ['iUTId' => $value['iBeforeUTId']]]);
                if ($beforeData) {
                    $schoolInfo = [['iSchoolId' => $beforeData->iSchoolId]];
                    School::runName($schoolInfo, ['iSchoolId' => 'sSchoolName']);
                    $value['beforePurpose'] = $enum['iReceivePurpose'][$beforeData->iReceivePurpose];
                    $value['beforeReceiver'] = $beforeData->sReceiverName;
                    $value['beforeNowReceiver'] = $beforeData->sNowReceiverName ? : '';
                    $value['beforeSchool'] = isset($schoolInfo[0]['sSchoolName']) ? $schoolInfo[0]['sSchoolName'] : '';
                    $value['beforeDevice'] = $beforeData->sDevNumber;
                }
            }
        }

        //计算页脚
        $footParams = [
            'columns' => 'count(DISTINCT(sReceiverPhone)) as receiverNum,sum(iReceivePurpose = 0) as selfNum,sum(iReceivePurpose = 1) as backNum',
            'conditions' => 'bDelete = 0 AND bHistory = 0'
        ];
        $footInfo = XhsysUsertablet::findFirst($footParams);
        $footParams['columns'] = 'count(DISTINCT(sReceiverPhone)) as receiverNum';
        $footParams['conditions'] .= ' AND iReceivePurpose = 1';
        $backInfo = XhsysUsertablet::findFirst($footParams);
        $data['footer'][] = [
            'sDevNumber'        => '上报人数：',
            'sDevType'          => $footInfo['receiverNum'],
            'sMacAddress'       => '上报备用机人数：',
            'sIMei'             => $backInfo['receiverNum'],
            'iReceiveStatus'    => '自用机：',
            'sReceiverName'     => $footInfo['selfNum'],
            'sReceiverPhone'    => '备用机：',
            'sReceiverAccount'  => $footInfo['backNum']
        ];
        return $this->sendJsonResponse($data);

//        $purpose = $this->request->getPost('purpose', 'int');
//        $done    = $this->request->getPost('done', 'int');
//        $status  = $this->request->getPost('status', 'int');
//        $school  = $this->request->getPost('school', 'string');
//        $mine    = !!$this->request->getPost('mine', 'int', 0);
//        $schoolId = $this->request->getPost('schoolId', 'string');
//        $iCIId    = $this->request->getPost('iCIId','int');
//        $condition = [];
//        if ($iCIId) {
//            $staffIds = $this->db->fetchAll("select iStaffId from XHCoop_Contact WHERE bDelete = 0 and iStaffId is not null and iCIId = {$iCIId} ");
//            $staffIds = array_values(array_filter(array_column($staffIds,'iStaffId')));
//            if (count($staffIds) > 0) {
//                $condition[] = 'B.iStaffId in (' . implode(',', $staffIds) . ') ';
////                $condition[] = 'iStaffId in (' . implode(',', $staffIds) . ') ';
//            }else{
//                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
//            }
//        }
//        if ($purpose != '') {
//            $condition[] = "B.iReceivePurpose = '{$purpose}'";
////            $condition[] = "iReceivePurpose = '{$purpose}'";
//        }
//        if ($done != '') {
//            $condition[] = "B.bDone = '{$done}'";
////            $condition[] = "bDone = '{$done}'";
//        }
//        if ($status) {
//            $condition[] = "B.iReceiveStatus = '{$status}'";
////            $condition[] = "iReceiveStatus = '{$status}'";
//        }
//        else {
//            $condition[] = "B.iReceiveStatus <> 3";
////            $condition[] = "iReceiveStatus <> 3";
//        }
//        if ($school) {
//            $condition[] = "C.sSchoolName like '%{$school}%'";
//        }
//        if ($schoolId) {
//            $condition[] = "C.iSchoolId = $schoolId";
////            $condition[] = "iSchoolId = $schoolId";
//        }
//        if ($mine) {
//            $phoneNum = XhhrmStaff::findFirst([
//                'conditions' => 'bDelete = 0 AND iUserId = :userId:',
//                'columns'    => 'sSelfPhone',
//                'bind'       => ['userId' => Main::getLoginUserInfo('userId')]
//            ])->sSelfPhone;
//            if (!$phoneNum) {
//                return $this->sendDataGridError('非员工无法查询');
//            }
////            $mineCondition = "B.sReceiverPhone = '{$phoneNum}'";
//            $mineCondition = "sReceiverPhone = '{$phoneNum}'";
//            $schoolIds = User::getSchoolPower(false, null, true);
//            if ($schoolIds === true) {
//                $mineCondition = '(' . $mineCondition . ' OR 1)';
//            }
//            else if ($schoolIds) {
//                $schoolIds = implode(',', $schoolIds);
//                $mineCondition = '(' . $mineCondition . " OR B.iSchoolId IN ({$schoolIds}))";
////                $mineCondition = '(' . $mineCondition . " OR iSchoolId IN ({$schoolIds}))";
//            }
//            $condition[] = $mineCondition;
//        }
//        $condition = implode(' AND ', $condition);
//        Main::runSearchVagueConditions($condition, ['sDevNumber', 'sDevType', 'sMacAddress', 'sReceiverName', 'sReceiverAccount', 'sReceiverPhone', 'sNowReceiverName', 'sNowReceiverAccount', 'sRealUserName', 'sRealUserAccount']);
//        $sql = [
//            'columns'   => 'B.*,C.sSchoolName',
//            'query'     => "SELECT :columns: FROM (SELECT * FROM (SELECT * FROM `XHSys_UserTablet` WHERE bDelete = 0 ORDER BY iUTId DESC) A GROUP BY sDevNumber ORDER BY iUTId DESC) B LEFT JOIN XHSchool_Info C on B.iSchoolId = C.iSchoolId WHERE {$condition}"
////            'query'     => "SELECT :columns: FROM (SELECT * FROM (SELECT * FROM `XHSys_UserTablet` WHERE bDelete = 0 AND {$condition} ORDER BY iUTId DESC) A GROUP BY sDevNumber ORDER BY iUTId DESC) B LEFT JOIN XHSchool_Info C on B.iSchoolId = C.iSchoolId"
//        ];
////        if ($school) {
////            $sql['query'] .= " WHERE C.sSchoolName like '%{$school}%'";
////        }
//        $data = Main::runSqlPage($sql, $this->registerEnum);
////        Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
//        Main::runUserName($data['rows'], ['iLastModifyUserId' => 'iLastModifyUserId']);
//
//        //计算页脚
//        $sql = 'SELECT count(DISTINCT(sReceiverPhone)) AS receiverNum,sum(iReceivePurpose = 0) as selfNum,sum(iReceivePurpose = 1) as backNum
//FROM (SELECT * FROM (SELECT * FROM `XHSys_UserTablet` WHERE bDelete = 0 ORDER BY iUTId DESC) A GROUP BY sDevNumber ORDER BY iUTId DESC) B';
//        $backSql = 'SELECT count(DISTINCT (sReceiverPhone)) as backReceiverNum
//FROM (SELECT * FROM (SELECT * FROM `XHSys_UserTablet` WHERE bDelete = 0 ORDER BY iUTId DESC) A GROUP BY sDevNumber ORDER BY iUTId DESC) B where iReceivePurpose = 1';
//        $info = $this->db->fetchOne($sql);
//        $backInfo = $this->db->fetchOne($backSql);
//        $data['footer'][] = [
//            'sDevNumber'        => '上报人数：',
//            'sDevType'          => $info['receiverNum'],
//            'sMacAddress'       => '上报备用机人数：',
//            'sReceiverName'     => $backInfo['backReceiverNum'],
//            'sReceiverAccount'  => '自用机：',
//            'sReceiverPhone'    => $info['selfNum'],
//            'iReceivePurpose'   => '备用机：',
//            'bDone'             => $info['backNum']
//        ];
//        return $this->sendJsonResponse($data);
    }

    /**
     * 根据id获取领用信息
     *
     * @param $id
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170920
     */
    public function getRegisterInfoAction($id)
    {
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        $obj = XhsysUsertablet::findFirst($id);
        if (!$obj) {
            return $this->sendErrorResponse(400, '找不到改记录信息');
        }
        return $this->sendJsonResponse($obj);
    }

    /**
     * 添加最后登录信息
     *
     * @param $data
     *
     * @return bool
     *
     * create by qgz 20181107
     */
    public function addLastLogInInfo(&$data)
    {
        if (!$data) {
            return true;
        }
        $computers = array_filter(array_unique(array_column($data, 'sDevNumber')));
        if (!$computers) {
            return true;
        } else {
            $computers = implode("','", $computers);
            $sql = " SELECT * FROM (SELECT lo_us_id, lo_computername, lo_date FROM login_log a WHERE a.lo_computername in ('" . $computers . "') ORDER BY lo_date DESC ) b GROUP BY lo_computername ";
            $loginInfo = $this->db->fetchAll($sql);
            if (!$loginInfo) {
                return true;
            } else {
                $loginInfo = array_column($loginInfo, null, 'lo_computername');
                foreach ($data as &$datum) {
                    if (isset($loginInfo[$datum['sDevNumber']])) {
                        $datum['logInName'] = $loginInfo[$datum['sDevNumber']]['lo_us_id'] ? $loginInfo[$datum['sDevNumber']]['lo_us_id'] : '';
                        $datum['logInTime'] = $loginInfo[$datum['sDevNumber']]['lo_date'] ? $loginInfo[$datum['sDevNumber']]['lo_date'] : '';
                    }
                }
                return true;
            }
        }
    }

    /**
     * 设备授权历史
     *
     * @return View
     *
     * create by qgz 20190219
     */
    public function registerHistoryAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/device/registerHistory.js');
        return $this->view->setVars([
            'List' => Template::createList('list', 'Register_History', [])
        ]);
    }

    /**
     * 获取授权历史数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190219
     */
    public function getRegisterHistoryAction()
    {
        $return = ['total' => 0, 'rows' => []];
        $device = $this->request->getPost('device');
        if (!$device) {
            return $this->sendJsonResponse($return);
        }
        $params = [
            'conditions' => 'bDelete = 0 and sDevNumber = :sDevNumber:',
            'bind' => ['sDevNumber' => $device],
            'order'      => 'iUTId desc'
        ];
        $enum = $this->registerEnum;
        $enum['iNewPurpose'] = $enum['iReceivePurpose'];
        $data = Main::runModelPage('\\Admin\\Models\\device\\XhsysUsertablet', $params, $enum);
        School::runName($data['rows'], ['iSchoolId' => 'sSchoolName']);
        foreach ($data['rows'] as &$value) {
            if ($value['iBeforeUTId']) {//加上记录的前身数据
                $beforeData = XhsysUsertablet::findFirst(['conditions' => 'iUTId = :iUTId:', 'bind' => ['iUTId' => $value['iBeforeUTId']]]);
                if ($beforeData) {
                    $schoolInfo = [['iSchoolId' => $beforeData->iSchoolId]];
                    School::runName($schoolInfo, ['iSchoolId' => 'sSchoolName']);
                    $value['beforePurpose'] = $enum['iReceivePurpose'][$beforeData->iReceivePurpose];
                    $value['beforeReceiver'] = $beforeData->sReceiverName;
                    $value['beforeNowReceiver'] = $beforeData->sNowReceiverName ? : '';
                    $value['beforeDevice'] = $beforeData->sDevNumber;
                    $value['beforeSchool'] = isset($schoolInfo[0]['sSchoolName']) ? $schoolInfo[0]['sSchoolName'] : '';
                }
            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 删除领用设备记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170619
     */
    public function delRegisterAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        if (!UserPower::checkUserPower('Device_registerList_Del')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        if (!XhsysUsertablet::deleteRecord('iUTId', $ids)){
            return $this->sendErrorResponse(500, '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }


    /**
     * 同步领用设备数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180608
     */
    public function synRegisterAction()
    {
        $idArr = $this->request->getPost('ids', 'int');
        if (!$idArr) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        $ids = implode(',', $idArr);
        $data = XhsysUsertablet::find([
            'columns' => 'iUTId, sDevNumber, sReceiverName, sReceiverAccount, sMacAddress, sDevType, sIMei',
            'conditions' => "bDelete = 0 and iUTId in ($ids)"
            ]);
        if (!$data){
            return $this->sendErrorResponse(500, '暂无数据');
        }
        $noLoginNum = $noChange = 0;
        $change = ['fail' => [], 'success' => []];
        $idInArr = $idOutArr = [];
        $data = $data->toArray();
        foreach($data as $value){
            $idInArr[] = $value['iUTId'];
            $isChange=false;
            $XhsysUsertablet = XhsysUsertablet::findFirst(['columns' => '*', 'conditions' => "bDelete = 0 and iUTId = ".$value['iUTId']]);
            $login_data = LoginLog::findFirst([
                'columns' => 'lo_id, lo_us_id, lo_uid, lo_computername, lo_mac, lo_model, lo_imei',
                'conditions' => "lo_computername = '".$value['sDevNumber']."'",//根据设备号查询
                'order' => 'lo_date DESC'
            ]);
            if (!$login_data){
                $noLoginNum++;
                $noChange++;
                $change['success'][] = $value;
                continue;
            }
            $login_data = $login_data->toArray();
            if ($login_data['lo_mac'] && ($login_data['lo_mac'] != $value['sMacAddress'])){
                $XhsysUsertablet->sMacAddress = $login_data['lo_mac'];
                $isChange = true;
            }
            if ($login_data['lo_model'] && ($login_data['lo_model'] != $value['sDevType'])){
                $XhsysUsertablet->sDevType = $login_data['lo_model'];
                $isChange = true;
            }
            if ($login_data['lo_imei'] && ($login_data['lo_imei'] != $value['sIMei'])){
                $XhsysUsertablet->sIMei = $login_data['lo_imei'];
                $isChange = true;
            }
            if ($isChange){
                $sql = "update XHSys_UserTablet set sMacAddress = '{$login_data['lo_mac']}', sDevType = '{$login_data['lo_model']}', sIMei = '{$login_data['lo_imei']}' where iUTId = {$value['iUTId']}";
                $final = $this->db->execute($sql);
                if (!$final){
                    $value['reason'] = '同步失败：id：' . $value['iUTId'];
                    $change['fail'][] = $value;
                    continue;
                }else{
                    $change['success'][] = $value;
                }
            }else{
                $noChange++;
                $change['success'][] = $value;
            }
            unset($XhsysUsertablet, $login_data);
        }
        $idOutArr = array_diff($idArr, $idInArr);
        $msg = '成功'.count($change['success']).'台;';//成功的数量
        if ($noChange != 0){
            $msg .= '[包括未改变' . $noChange . '台];';//数据未改变
        }
        if ($noLoginNum != 0){
            $msg .= '[包括找不到可同步数据' . $noLoginNum . '台];';//日志表找不到数量
        }
        if (!empty($idOutArr)){
            $msg .= '找不到设备数据' . count($idOutArr) . '台;';//领用表找不到数量
        }
        if(count($change['fail']) > 0){
            $msg .= '失败' . count($change['fail']) . '台;';//失败的数量
        }
        $return = [
            'msg' => $msg,
            'noFindNum' => $noLoginNum,
            'successNum' => count($change['success']),
            'errorNum' => count($change['fail']),
            'errorData' => $change['fail']//失败的数据
        ];
        return $this->sendJsonResponse($return);
    }

    /**
     * 设备维修--领用列表
     *
     * @return string
     *
     * create by qgz 20180611
     */
    public function showRegisterRepairAction(){
        Assets::select2();
        Assets::easyUI('js/device/registerRepairForm.js');
        $this->view->pick('device/registerRepairForm');

        $id = $this->request->getQuery('id');
        $parameters = [
            'columns' => 'sReceiverAccount, sDevType, sDevNumber, sIMei, iSchoolId, iReceivePurpose',
            'conditions' => ' bDelete = 0 and iUTId = :iUTId:',
            'bind' => ['iUTId' => $id]
        ];
        $data = XhsysUsertablet::findFirst($parameters);
        if (!$data){
            return $this->sendViewError('暂无设备数据');
        } else {
            $data = $data->toArray();
        }
        $userId = $userName = '';
        $userInfo = XhsysUser::findFirst([
            'columns' => 'iUserId, sUserName',
            'conditions' => 'bDelete = 0 and sLogonName = :sLogonName:',
            'bind' => ['sLogonName' => $data['sReceiverAccount']]
        ]);
        if ($userInfo){
            $userId = $userInfo->iUserId;
            $userName = $userInfo->sUserName;
        }
        $this->view->setVars([
            'id' => $userId,
            'schoolId' => $data['iSchoolId'],
            'sLogonName' => $data['sReceiverAccount'],
            'sUserName' => $userName,
            'sModel' => $data['sDevType'],
            'sDeviceNumber' => $data['sDevNumber'],
            'sImei' => $data['sIMei'],
            'iReceivePurpose' => $this->registerEnum['iReceivePurpose'][$data['iReceivePurpose']]
        ]);
    }

    /**
     * 标记为已使用状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170920
     */
    public function doneRegisterAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        if (!UserPower::checkUserPower('School_List_Spare')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $result = $this->modelsManager->executeQuery('update \\Admin\\Models\\device\\XhsysUsertablet set bDone = 1 where iUTId in ({ids:array})', ['ids' => $ids]);
        if (!$result) {
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('标记成功');
    }

    /**
     * 标记为归还状态，并标记使用完毕
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171206
     */
    public function returnRegisterAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        if (!UserPower::checkUserPower('Device_registerList_Done')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $result = $this->modelsManager->executeQuery('update \\Admin\\Models\\device\\XhsysUsertablet set bDone = 1, iReceiveStatus = 3 where iUTId in ({ids:array})', ['ids' => $ids]);
        if (!$result) {
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 创建领用记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170920
     */
    public function createRegisterAction()
    {
        try {
            $tablet = new XhsysUsertablet();
            $tablet->assign($this->request->getPost());
            if (!$tablet->sDevNumber || !$tablet->sReceiverName || !$tablet->sReceiverPhone) {
                return $this->sendErrorResponse(400, '缺少必要参数');
            }
            $check = XhsysUsertablet::findFirst([
                'conditions' => 'bDelete = 0 AND bDone = 0 AND sDevNumber = :devNumber:',
                'bind'       => ['devNumber' => $tablet->sDevNumber]
            ]);
            if ($check) {
                return $this->sendErrorResponse(400, '该设备正在使用中，无法新增');
            }
            if (!$tablet->save()) {
                return $this->sendErrorResponse(500, '新增失败');
            }
            return $this->sendSuccessResponse('新增成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '新建失败', $e->getMessage());
        }
    }

    /**
     * 修改领用记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170920
     */
    public function modifyRegisterAction()
    {
        $id = $this->request->getPost('iUTId', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        try {
            $tablet = XhsysUsertablet::findFirst($id);
            $tablet->assign($this->request->getPost());
            if (!$tablet->sDevNumber || !$tablet->sReceiverName || !$tablet->sReceiverPhone) {
                return $this->sendErrorResponse(400, '缺少必要参数');
            }
            if (!$tablet->save()) {
                return $this->sendErrorResponse(500, '修改失败');
            }
            return $this->sendSuccessResponse('修改成功');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, '保存失败', $e->getMessage());
        }
    }

    /**
     * 用户使用备用机页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20170927
     */
    public function spareRegisterAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/device/spareRegister.js');
        $logonName = $this->request->getQuery('logonName', 'string');
        if (!$logonName) {
            return $this->sendViewError('缺少账号信息');
        }
        if (!UserPower::checkUserPower('School_List_Spare')){
            return $this->sendViewError('无查看此页面权限');
        }
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_item', 'multiple' => 'true', 'style' => 'width:110px;', 'data' => [
            ''                      => '默认',
            'sDevNumber'            => '设备号',
            'sDevType'              => '设备型号',
            'sMacAddress'           => 'MAC地址',
            'sReceiverName'         => '领用人',
            'sReceiverAccount'      => '领用账号',
            'sReceiverPhone'        => '领用手机',
            'sNowReceiverName'      => '当前领用人',
            'sNowReceiverAccount'   => '当前领用账号'
        ]];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHSys_UserTablet', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr),
                'tableAttr'     => ['singleSelect' => 'true']
            ]),
        ]);
    }

    /**
     * 获取可使用备用机列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170927
     * modify by ck 20171012    修复BUG
     * modify by ck 20180410    仅显示已领用列表
     * modify by ck 20180828    重构
     */
    public function getSpareRegisterAction()
    {
        $params = [
            'conditions' => 'bDelete = 0 AND bHistory = 0 AND iReceivePurpose = 1 AND (bDone = 1 OR IFNULL( sNowReceiverAccount, "" ) = "") AND iReceiveStatus = 2'
        ];
        Main::runSearchVagueConditions($params['conditions'], ['sDevNumber', 'sDevType', 'sMacAddress', 'sReceiverName', 'sReceiverAccount', 'sReceiverPhone', 'sNowReceiverName', 'sNowReceiverAccount']);
        $data = Main::runModelPage('\\Admin\\Models\\device\\XhsysUsertablet', $params, $this->registerEnum);
        return $this->sendJsonResponse($data);
        //        $conditions = 'bDelete = 0 AND iReceivePurpose = 1 AND (bDone = 1 OR IFNULL( sNowReceiverAccount, "" ) = "") AND iReceiveStatus = 2';
//        Main::runSearchVagueConditions($conditions,
//            ['sDevNumber', 'sDevType', 'sMacAddress', 'sReceiverName', 'sReceiverAccount', 'sReceiverPhone', 'sNowReceiverName', 'sNowReceiverAccount']);
//        return $this->sendJsonResponse(Main::runSqlPage([
//            'query'   => "SELECT :columns: FROM (SELECT * FROM (SELECT * FROM XHSys_UserTablet ORDER BY iUTId DESC) t GROUP BY sDevNumber) t WHERE {$conditions}",
//            'columns' => '*'
//        ], $this->registerEnum));

//        $total = $this->db->fetchOne('SELECT count(*) as total FROM (SELECT * FROM XHSys_UserTablet WHERE bDelete = 0 AND iReceivePurpose = 1 AND (bDone = 1 OR IFNULL( sNowReceiverAccount, "" ) = "") ORDER BY iUTId DESC ) table1 GROUP BY sDevNumber')['total'];
//        $rows  = $this->db->fetchAll('SELECT * FROM (SELECT * FROM XHSys_UserTablet WHERE bDelete = 0 AND iReceivePurpose = 1 AND (bDone = 1 OR IFNULL( sNowReceiverAccount, "" ) = "") ORDER BY iUTId DESC ) table1 GROUP BY sDevNumber');
//        return $this->sendJsonResponse(['total' => $total, 'rows' => $rows]);

//        $parameters = [
//            'conditions' => 'bDelete = 0 AND iReceivePurpose = 1 AND (bDone = 1 OR IFNULL(sNowReceiverAccount, "") = "")',
//            'order'      => 'iUTId DESC',
//            'group'      => 'sDevNumber'
//        ];
//        Main::runSearchVagueConditions($parameters['conditions'],
//            ['sDevNumber', 'sDevType', 'sMacAddress', 'sReceiverName', 'sReceiverAccount', 'sReceiverPhone', 'sNowReceiverName', 'sNowReceiverAccount']);
//        $data = Main::runModelPage('\\Admin\\Models\\device\\XhsysUsertablet', $parameters, $this->registerEnum);
//        return $this->sendJsonResponse($data);
    }

    /**
     * 用户使用备用机
     *
     * @param  $code string  设备码
     * @param  $userId int   学生老师id
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170927
     * modify by dale 20171208
     * modify by ck 20180112    添加验证
     * modify by ck 20180410    根据设备号获取id改为最后一条
     * modify by ck 20180525    添加当前领用人id
     */
    public function useSpareRegisterAction($code = null, $userId = null)
    {
        if(!$code && !$userId){
            $registerId = $this->request->getPost('registerId', 'int');
            $logonName  = $this->request->getPost('logonName', 'string');
        }
        else{
            $tab = XhsysUsertablet::findFirst([
                'conditions' => 'sDevNumber = :code: AND bDelete = 0',
                'bind'       =>  ['code' => $code],
                'order'      => 'iUTId desc'
            ]);
            if(!$tab){
                return $this->sendErrorResponse(400, '没找到该设备号的平板');
            }
            $registerId = $tab->iUTId;
            $logonName  = User::getLogonName($userId);
        }
        if (!$registerId || !$logonName) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            $this->db->begin();
            $register = XhsysUsertablet::findFirst($registerId);
//            if (!$register->bDone) {
//                $register->bDone = 1;
//                if (!$register->save()) {
//                    throw new \Exception('操作失败');
//                }
//            }
            $check = XhsysUsertablet::count([
                'conditions' => 'sNowReceiverAccount = :logonName: AND bDelete = 0 AND bDone = 0',
                'bind'       => ['logonName' => $logonName]
            ]);
            if ($check) {
                throw new \Exception('该用户已使用备用机，不可继续使用');
            }
            $check = XhsysUsertablet::findFirst([
                'conditions' => 'sDevNumber = :devNumber: AND bDelete = 0',
                'bind'       => ['devNumber' => $register->sDevNumber],
                'order' => 'iUTId desc'
            ]);
            if (!$check->bDone) {
                throw new \Exception('该设备未使用完毕，不可使用');
            }
            $register->iUTId                = null;
            $register->iNowReceiverId       = $userId;
            $register->sNowReceiverAccount  = $logonName;
            $register->tNowReceiveTime      = date('Y-m-d H:i:s');
            $register->bDone                = 0;
            $register->sNowReceiverName     =  XhsysUser::findFirst([
                'columns'    => 'sUserName',
                'conditions' => 'bDelete = 0 AND sLogonName = :logonName:',
                'bind'       => ['logonName' => $logonName]
            ])->sUserName;
            $register->iReceiveStatus == 3 and $register->iReceiveStatus = 1;
            if (!$register->save()) {
                throw new \Exception('操作失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('使用成功');
        }
        catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 生成领用二维码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171207
     * modify by ck 20180413    增加教师机领用
     */
    public function receiveRegisterQRAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        try {
            //检查设备类型
            $devType = XhsysUsertablet::find([
                'columns'    => 'iReceivePurpose as purpose',
                'conditions' => 'bDelete = 0 AND iUTId IN ({idArr:array})',
                'group'      => 'purpose',
                'bind'       => ['idArr' => $ids]
            ])->toArray();
            if (count($devType) > 1) {
                return $this->sendErrorResponse(400, '不可同时选择多种类型');
            }
            if ($devType[0]['purpose'] != 3) {
                $registers = XhsysUsertablet::find([
                    'columns'    => 'count(*) as count,sum(iReceiveStatus = 1) as needReceive,sReceiverPhone as phone',
                    'conditions' => 'bDelete = 0 AND iUTId IN ({idArr:array})',
                    'group'      => 'sReceiverPhone',
                    'bind'       => ['idArr' => $ids]
                ])->toArray();
                if (count($registers) == 0) {
                    return $this->sendErrorResponse(400, '参数异常，无记录');
                }
                elseif (count($registers) > 1) {
                    return $this->sendErrorResponse(400, '选中领用必须为同一人');
                }
                if (count($ids) > $registers[0]['needReceive']) {
                    return $this->sendErrorResponse(400, '选中包含非<待领用>记录');
                }
            }
            else {
                $devCount = XhsysUsertablet::count([
                    'conditions' => 'bDelete = 0 AND iReceiveStatus = 1 AND iUTId IN ({idArr:array})',
                    'bind'       => ['idArr' => $ids]
                ]);
                if (count($ids) > $devCount) {
                    return $this->sendErrorResponse(400, '选中包含非<待领用>记录');
                }
            }

//            ob_start();
//            QRcode::png(
//                Tool::buildUrl('Device/receiveRegister', ['ids' => implode(',', $ids)]),
//                false, 0, 10, 1
//            );
//            $imgString = base64_encode(ob_get_contents());
//            ob_end_clean();
            return $this->sendSuccessResponse(
                Tool::getQRBase64Uri(
                    Tool::buildUrl('Device/receiveRegister', ['ids' => implode(',', $ids)])
                ),
            false);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 领用设备
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171207
     * modify by ck 20180413    支持教师机领用
     */
    public function receiveRegisterAction()
    {
        $params = $this->request->getQuery('ids', 'string');
        $ids    = explode(',', $params);
        if (!$ids) {
            return $this->sendViewError('参数错误');
        }
        try {
            //检查设备类型
            $devType = XhsysUsertablet::find([
                'columns'    => 'iReceivePurpose as purpose',
                'conditions' => 'bDelete = 0 AND iUTId IN ({idArr:array})',
                'group'      => 'purpose',
                'bind'       => ['idArr' => $ids]
            ])->toArray();
            if (count($devType) > 1) {
                return $this->sendViewError('不可同时选择多种类型');
            }
            if ($devType[0]['purpose'] != 3) {
                $registers = XhsysUsertablet::find([
                    'columns'    => 'count(*) as count,sum(iReceiveStatus = 1) as needReceive,sReceiverPhone as phone',
                    'conditions' => 'bDelete = 0 AND iUTId IN ({idArr:array})',
                    'group'      => 'sReceiverPhone',
                    'bind'       => ['idArr' => $ids]
                ])->toArray();
                if (count($registers) == 0) {
                    return $this->sendViewError('参数异常，无记录');
                } elseif (count($registers) > 1) {
                    return $this->sendViewError('领用设备必须为同一人');
                }
                if (count($ids) > $registers[0]['needReceive']) {
                    return $this->sendViewError('选中包含非<待领用>记录');
                }
                $staff = XhhrmStaff::findFirst([
                    'columns'    => 'iUserId',
                    'conditions' => 'bDelete = 0 AND sSelfPhone = :phone:',
                    'bind'       => ['phone' => $registers[0]['phone']]
                ]);
                if (!$staff) {
                    return $this->sendViewError('找不到员工信息');
                }
                if ($staff->iUserId != Main::getLoginUserInfo('userId')) {
                    return $this->sendViewError('设备领用人错误');
                }
            }
            else {
                $devCount = XhsysUsertablet::count([
                    'conditions' => 'bDelete = 0 AND iReceiveStatus = 1 AND iUTId IN ({idArr:array})',
                    'bind'       => ['idArr' => $ids]
                ]);
                if (count($ids) > $devCount) {
                    return $this->sendViewError('选中包含非<待领用>记录');
                }
            }
            $result = $this->modelsManager->executeQuery('update \\Admin\\Models\\device\\XhsysUsertablet set iReceiveStatus = 2 where iUTId in ({idArr:array})', ['idArr' => $ids]);
            if (!$result) {
                return $this->sendViewError('领用失败');
            }
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
        return $this->sendViewSuccess('领用成功');
    }

    /**
     * 设置领用机学校id
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180223
     */
    public function setRegisterSchoolAction()
    {
        $ids        = $this->request->getPost('ids', 'int');
        $schoolId   = $this->request->getPost('schoolId', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校不能为空');
        }
        try {
            $result = $this->modelsManager->executeQuery('update \\Admin\\Models\\device\\XhsysUsertablet set iSchoolId = :schoolId: where iUTId in ({idArr:array}) and iReceivePurpose = 1', ['schoolId' => $schoolId, 'idArr' => $ids]);
            if (!$result) {
                throw new \Exception('操作失败');
            }
            return $this->sendSuccessResponse('操作成功');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 绑定设备列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171201
     * modify by ck 20180928
     */
    public function boundAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/device/bound.js');
        if (!UserPower::checkUserPower('Device_Bound')){
            return $this->sendViewError('无查看此页面权限');
        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_status', 'style' => 'width:60px;', 'data' => [0 => '全部', 1 => '正常', 2 => '历史']];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        if (UserPower::checkUserPower('Device_Bound_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_unbind', 'text' => '解除绑定', 'plain' => 'true', 'icon' => 'fa-chain-broken'];
            $listButtonArr[] = ['id' => 'bt_list_rebind', 'text' => '恢复绑定', 'plain' => 'true', 'icon' => 'fa-chain'];
        }
        return $this->view->setVars([
            'List'          => Template::createList('list', 'Device_Bound', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取绑定列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171201
     */
    public function getBoundAction()
    {
        $status = $this->request->getPost('status', 'int', 0);
        $sort   = $this->request->getPost('sort', 'string');
        $order  = $this->request->getPost('order', 'string');
        $userId = $this->request->getPost('userId', 'string');
        $devNum = $this->request->getPost('devNum', 'string');
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns(['a.iADLId', 'a.iUserId', 'a.sLogonName', 'a.sDeviceNumber', 'a.sMac', 'a.sIP', 'a.sModel',
                    'a.tCreateDate', 'b.iSchoolId', 'a.bDelete', 'a.tLastModifyDate', 'a.iNewUserId', 'a.sNewDevice'])
                ->from(['a' => '\\Admin\\Models\\device\\XhsysAccountdevicelocked'])
                ->leftJoin('\\Admin\\Models\\user\\XhsysUser', 'b.iUserId = a.iUserId', 'b')
                ->orderBy('a.iADLId DESC');
            if ($status) {
                $builder->andWhere('a.bDelete = :status:', ['status' => $status - 1]);
            }
            if ($userId) {
                $builder->andWhere('a.iUserId = :userId:', ['userId' => $userId]);
            }
            if ($devNum) {
                $builder->andWhere('a.sDeviceNumber = :devNum:', ['devNum' => $devNum]);
            }
            if ($sort) {
                if ($sort == 'sUserName') {
                    $sort = 'iUserId';
                } elseif ($sort == 'sNewUserName') {
                    $sort = 'sNewDevice';
                }
                $builder->orderBy('a.' . $sort . ' ' . $order);
            }

            $conditions = '';
            Main::runSearchVagueConditions($conditions, ['a.sDeviceNumber', 'a.sMac', 'a.sIP', 'b.sUserName', 'a.iUserId', 'a.sLogonName', 'a.iNewUserId', 'a.sNewDevice']);
            if ($conditions) {
                $builder->andWhere($conditions);
            }
            $data = Main::runBuilderPage($builder, $this->registerEnum['bDelete']);
            Main::runUserName($data['rows'], ['iUserId' => 'sUserName', 'iNewUserId' => 'sNewUserName']);
            Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 解除绑定
     *
     * @param array $ids
     * @param int $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *s
     * create by ck 20171201
     * modify by ck 20171220    学校解绑及归还借用合并
     * modify by ck 20180824    指定默认值
     */
    public function unbindBoundAction($ids = [], $type = 0)
    {
        if(!$ids) {
            $ids  = $this->request->getPost('ids', 'int');
            $type = $this->request->getPost('type', 'int', 0);
        }
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        switch ($type) {
            case 0: $powerTag = 'Device_Bound_Del'; break;
            case 1: //$powerTag = 'School_List_Stud_Device'; break;
            case 2: $powerTag = 'School_List_Spare'; break;
            default: $powerTag = 'Device_Bound_Del';
        }
        if (!UserPower::checkUserPower($powerTag)) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            $parameters = [
                'conditions' => 'bDelete = 0 AND iADLId IN ({idArr:array})',
                'bind'       => ['idArr' => $ids]
            ];
            if ($type) {
                $parameters['conditions'] .= ' AND iSourceType = :type:';
                $parameters['bind']['type']= $type;
            }
            $data = XhsysAccountdevicelocked::find($parameters);
            if (!count($data)) {
                return $this->sendErrorResponse(400, '无可操作数据');
            }
            $result = $data->delete();
            if (!$result) {
                return $this->sendErrorResponse(500, '操作失败');
            }
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 重新绑定
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180928
     */
    public function rebindBoundAction()
    {
        $ids  = $this->request->getPost('ids', 'int');
        $parameters = [
            'conditions' => 'iADLId IN ({idArr:array})',
            'bind'       => ['idArr' => $ids]
        ];
        try {
            $this->db->begin();
            $data = XhsysAccountdevicelocked::find($parameters);
            foreach ($data as $row) {
                $row->bDelete = 0;
                if (!$row->save()) {
                    throw new \Exception($row->getError());
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('恢复成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 借用设备
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171219
     * modify by ck 20171220
     */
    public function borrowTabletAction()
    {
        $userId    = $this->request->getPost('userId', 'int');
        $devNumber = $this->request->getPost('devNumber', 'string');
        if (!$userId || !$devNumber) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            //检查是否允许借用，否则报异常
            Device::allowBorrow($userId, $devNumber);
            //获取原记录，新建记录
            $bindDev = XhsysAccountdevicelocked::findFirst([
                'conditions' => 'bDelete = 0 AND sDeviceNumber = :devNumber:',
                'bind'       => ['devNumber' => $devNumber]
            ]);
            $bindDev->iADLId      = null;
            $bindDev->iSourceType = 2;
            $bindDev->sSourceId   = $bindDev->iUserId;
            $bindDev->iUserId     = $userId;
            $bindDev->sLogonName  = User::getLogonName($userId);
            if (!$bindDev->save()) {
                throw new \Exception('借用失败：' . $bindDev->getMessages()[0]);
            }
            return $this->sendSuccessResponse('借用成功');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 设备审核页
     *
     * @return mixed
     *
     * create by qgz 20180507
     */
    public function deviceCheckAction()
    {
        $this->view->setTemplateBefore('listForm');
        if (!UserPower::checkUserPower('Device_Check')){
            return $this->sendViewError('无查看此页面权限');
        }
        Main::showNavPosition();
        Assets::easyUI('js/device/deviceCheck.js');
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'school_area', 'style' => 'width: 120px;'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_school', 'style' => 'width:100px;', 'label' => '    学校：'];
        if (UserPower::checkUserPower('Device_Check_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_check', 'text' => '审核', 'plain' => 'true', 'icon' => 'fa-check'];
            $listButtonArr[] = ['id' => 'bt_list_remark', 'text' => '备注', 'plain' => 'true', 'icon' => 'fa-pencil-square-o'];
        }
        if (UserPower::checkUserPower('Device_CheckHistory')){
            $listButtonArr[] = ['id' => 'bt_list_history', 'text' => '审核历史', 'plain' => 'true', 'icon' => 'fa-history'];
        }
        if (UserPower::checkUserPower('Device_Check_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_delCheck', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHSys_DeviceCheck', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr,true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取设备数
     *
     * @return mixed
     *
     * create by qgz 20180507
     * modify by ck 20180830    重构
     */
    public function getDeviceInfoAction()
    {
        $school = $this->request->getPost('school', 'string');
        $school_area = $this->request->getPost('school_area');
        try {
            $params = [
                'columns'    => 'iSchoolId, SUM(iReceivePurpose = 0) as zyj, SUM(iReceivePurpose = 1) as byj, SUM(iReceivePurpose = 2) as gyj ,SUM(iReceivePurpose = 3) as jsj',
                'conditions' => 'bDelete = 0 AND bHistory = 0 AND IFNULL(iSchoolId, 0) <> 0 AND iReceiveStatus <> 3',
                'group'      => 'iSchoolId'
            ];
            if (!empty($school_area)){
                $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$school_area},%'");
                if (!$staff['iUserId']) {
                    return $this->sendErrorResponse(500, '找不到该部门负责人');
                }
                $schoolArr = User::getSchool(true, $staff['iUserId'], true);
                if (!empty($schoolArr)){
                    $schoolId = implode(',', array_keys($schoolArr));
                    $params['conditions'] .= " and iSchoolId in ($schoolId)";
                }
            }

            $schoolPowerIds = School::getPower();
            if (!$schoolPowerIds) {
                return $this->sendDataGridError('无学校权限');
            }
            else if ($schoolPowerIds !== true) {
                $params['conditions'] .= ' AND iSchoolId IN ({schoolIds:array})';
                $params['bind']['schoolIds'] = $schoolPowerIds;
            }

            //学校搜索条件过滤
            if ($school) {
                $schoolSearchIds = School::searchSchool($school);
                if (!$schoolSearchIds) {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                }
                $params['conditions'] .= ' AND iSchoolId IN ({schoolSearchIds:array})';
                $params['bind']['schoolSearchIds'] = $schoolSearchIds;
            }

            $data = Main::runModelPage('\\Admin\\Models\\device\\XhsysUsertablet', $params);
            School::runName($data['rows'], ['iSchoolId' => 'sSchoolName']);
            if ($data['total'] != 0){
                $schoolIds = array_column($data['rows'], 'iSchoolId');
                $schoolIds = implode(",", $schoolIds);
                $remarkData = XhsysDevicecheck::find([
                    'columns' => 'iSchoolId, sRemarkData',
                    'conditions' => "bDelete = 0 AND iDataType = 2 AND iSchoolId in ($schoolIds)"
                ])->toArray();
                $remarkData = array_column($remarkData, 'sRemarkData', 'iSchoolId');
                $checkIds = $this->getCheckIds($data['rows']);
                foreach ($data['rows'] as &$value){
                    if (in_array($value['iSchoolId'], $checkIds['in'])){
                        $value['status'] = '<i class="fa fa-check" title="数量状态正常" style="color:green;" ></i>';
                    } else {
                        $value['status'] = '<i class="fa fa-exclamation-circle" title="未审核或数量发生变化，请再次确认" style="color:red;" ></i>';
                    }
                    $value['sRemarkData'] = isset($remarkData[$value['iSchoolId']]) ? $remarkData[$value['iSchoolId']] : '';
                    $value['haveHistory'] = in_array($value['iSchoolId'], $checkIds['haveChecked']) ? '<i class="fa fa-bell-o" title="有审核历史记录" ></i>' : '';
                }
            }
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
//        $schoolinfo = $this->request->getPost('school');
//        try {
//            $condition = "B.iSchoolId is NOT null AND B.iSchoolId <> 0 AND B.iReceiveStatus <> 3";
//            if ($schoolinfo){
//                $condition .= " and C.sSchoolName like '%{$schoolinfo}%'";
//            }
//
//            $schoolPowerIds = User::getSchoolPower(false, null, true);
//            if ($schoolPowerIds !== true) {
//            	if (!empty($schoolPowerIds)){
//		            $schoolPowerIds = implode(',', $schoolPowerIds);
//		            $condition .= " and B.iSchoolId in ($schoolPowerIds)";
//	            } else {
//		            $condition .= " and B.iSchoolId = -1 ";
//	            }
//            }
//            $sql = [
//                'columns' => "C.sSchoolName,B.iSchoolId, SUM(B.iReceivePurpose = '0') as zyj , SUM(B.iReceivePurpose = '1') as byj , SUM(B.iReceivePurpose = '2') as gyj ,SUM(B.iReceivePurpose = '3') as jsj",
//                'query' => "SELECT :columns: FROM ( SELECT * FROM ( SELECT * FROM `XHSys_UserTablet` WHERE bDelete = 0 ORDER BY iUTId DESC ) A GROUP BY sDevNumber ORDER BY tReceiveTime DESC ) B LEFT JOIN `XHSchool_Info` C ON B.iSchoolId = C.iSchoolId WHERE {$condition} GROUP BY B.iSchoolId "
//            ];
//            $data = Main::runSqlPage($sql);
//            if ($data['total'] != 0){
//                $schoolIds = array_column($data['rows'], 'iSchoolId');
//                $schoolIds = implode(",", $schoolIds);
//                $remarkData = XhsysDevicecheck::find([
//                    'columns' => 'iSchoolId, sRemarkData',
//                    'conditions' => "bDelete = 0 AND iDataType = 2 AND iSchoolId in ($schoolIds)"
//                ])->toArray();
//                $remarkData = array_column($remarkData, 'sRemarkData', 'iSchoolId');
//                $checkIds = $this->getCheckIds($data['rows']);
//                foreach ($data['rows'] as &$value){
//                    if (in_array($value['iSchoolId'], $checkIds['in'])){
//                        $value['status'] = '<i class="fa fa-check" title="数量状态正常" style="color:green;" ></i>';
//                    } else {
//                        $value['status'] = '<i class="fa fa-exclamation-circle" title="未审核或数量发生变化，请再次确认" style="color:red;" ></i>';
//                    }
//                    $value['sRemarkData'] = isset($remarkData[$value['iSchoolId']]) ? $remarkData[$value['iSchoolId']] : '';
//                    $value['haveHistory'] = in_array($value['iSchoolId'], $checkIds['haveChecked']) ? '<i class="fa fa-bell-o" title="有审核历史记录" ></i>' : '';
//                }
//            }
//            return $this->sendJsonResponse($data);
//        }
//        catch (\Exception $e){
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
    }

    /**
     * 获取审核情况id
     *
     * @param $schoolInfo
     *
     * @return array
     * @throws \Exception
     *
     * create by qgz 20180508
     */
    public function getCheckIds($schoolInfo = [])
    {
        $return = ['in' => [], 'out' => [], 'haveChecked' => []];//in为已经确认且数据一致，out为未确认或数据不一致,haveChecked为存在审核历史
        if (empty($schoolInfo)){
            return $return;
        }
        $schoolIds = array_column($schoolInfo, 'iSchoolId');
        $schoolInfo = array_combine($schoolIds, $schoolInfo);
        $sql = 'SELECT * FROM ( SELECT iSchoolId, iZyj, iByj, iGyj, iJsj, tCheckDate FROM XHSys_DeviceCheck AS a WHERE bDelete = 0 AND iDataType = 1 AND tCheckDate = 
                ( SELECT max(b.tCheckDate) FROM XHSys_DeviceCheck AS b WHERE a.iSchoolId = b.iSchoolId AND b.iDataType = 1 ) ) AS a WHERE iSchoolId in ('.implode(',', $schoolIds).') GROUP BY iSchoolId';
        try{
            $data = $this->db->fetchAll($sql);
        }catch (\Exception $e){
            throw $e;
        }
        if (empty($data)){
            return $return;
        }
        $params = [
        	'columns' => 'iSchoolId',
	        'conditions' => ' bDelete = 0 AND iDataType = 1 AND iSchoolId IN ({Arr:array})',
	        'bind' => ['Arr' => $schoolIds],
	        'group' => 'iSchoolId'
        ];
        $findData = XhsysDevicecheck::find($params)->toArray();
        if (!empty($findData)){
	        $return['haveChecked'] = array_column($findData, 'iSchoolId');//检测是否存在历史
        }
        $haveChecked = array_column($data, 'iSchoolId');
        $out = array_diff($schoolIds, $haveChecked);
        if (!empty($out)){
            $return['out'] = array_merge($return['out'], $out);
        }
        foreach ($data as $value){
            $school = $schoolInfo[$value['iSchoolId']];
            if ($value['iZyj'] == $school['zyj'] && $value['iByj'] == $school['byj'] && $value['iGyj'] == $school['gyj'] && $value['iJsj'] == $school['jsj']){
                $return['in'][] = $value['iSchoolId'];
            }else{
                $return['out'][] = $value['iSchoolId'];
            }
        }
        return $return;
    }

    /**
     * 审核设备，记录入库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     * @throws \Exception
     *
     * create by qgz 20180507
     */
    public function checkInfoAction()
    {
        $schoolIdsArr = $this->request->getPost('schoolIds');
        $checkRemark = $this->request->getPost('checkRemark');
        if (empty($schoolIdsArr)){
            return $this->sendErrorResponse(400, '请选择后操作');
        }
        $schoolIds = implode(',', $schoolIdsArr);
        $condition = "B.iSchoolId is NOT null AND B.iSchoolId <> 0 AND B.iReceiveStatus <> 3 AND B.bHistory = 0 AND B.iSchoolId in ($schoolIds)";
        $sql = [
            'columns' => "C.sSchoolName,B.iSchoolId, SUM(B.iReceivePurpose = '0') as zyj , SUM(B.iReceivePurpose = '1') as byj , SUM(B.iReceivePurpose = '2') as gyj ,SUM(B.iReceivePurpose = '3') as jsj",
            'query'   => "SELECT :columns: FROM ( SELECT * FROM ( SELECT * FROM `XHSys_UserTablet` WHERE bDelete = 0 ORDER BY iUTId DESC ) A ORDER BY tReceiveTime DESC ) B LEFT JOIN `XHSchool_Info` C ON B.iSchoolId = C.iSchoolId WHERE {$condition} GROUP BY B.iSchoolId "
        ];
        $data = Main::runSqlPage($sql);
        if ($data['total'] != 0){
            $checkIds = $this->getCheckIds($data['rows']);
            foreach ($data['rows'] as $row){
                if (!in_array($row['iSchoolId'], $checkIds['in'])){
                    $check_data = new XhsysDevicecheck();
                    $check_data->iSchoolId = $row['iSchoolId'];
                    $check_data->sSchoolName = $row['sSchoolName'];
                    $check_data->iZyj = $row['zyj'];
                    $check_data->iByj = $row['byj'];
                    $check_data->iGyj = $row['gyj'];
                    $check_data->iJsj = $row['jsj'];
                    $check_data->sRemarkData = $checkRemark;
                    $check_data->tCheckDate = date('Y-m-d H:i:s', time());
                    if (!$check_data->save()){
                        return $this->sendErrorResponse(500, '信息保存出错');
                    }
                }
            }
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 删除设备历史审核
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180620
     */
    public function delCheckHistoryAction()
    {
        $schoolId = $this->request->getPost('schoolId');
        if (!$schoolId){
            return $this->sendErrorResponse(400, '请选择后操作');
        }
        $data = XhsysDevicecheck::findFirst([
            'columns' => '*',
            'conditions' => 'bDelete = 0 and iSchoolId = :iSchoolId:',
            'bind' => ['iSchoolId' => $schoolId],
            'order' => 'tCheckDate DESC'
        ]);
        if (!$data){
            return $this->sendErrorResponse(500, '没有最新的操作');
        }
        $date = $data->tCheckDate;
        $sql = "update XHSys_DeviceCheck set bDelete = 1 where bDelete = 0 AND iSchoolId = $schoolId AND tCheckDate = '$date' ";
        $data = $this->db->execute($sql);
        if (!$data){
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 设置备注
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180622
     */
    public function setCheckRemarkAction()
    {
        $schoolIdArr = $this->request->getPost('schoolIds');
        $remark = $this->request->getPost('remark');
        if (empty($schoolIdArr)){
            return $this->sendErrorResponse(400, '参数错误');
        }
        $schoolIds = implode(",", $schoolIdArr);
        $existRemarkData = XhsysDevicecheck::find([
            'columns' => 'iSchoolId',
            'conditions' => "bDelete = 0 AND iDataType = 2 AND iSchoolId in ($schoolIds)"
        ])->toArray();
        $existRemarkData = array_column($existRemarkData, 'iSchoolId');
        $time = date('Y-m-d H:i:s', time());
        $userId = User::getId();
        if (!empty($existRemarkData)){
            $existSchoolId = implode(",", $existRemarkData);
            $sql = "update XHSys_DeviceCheck set sRemarkData = '$remark', iLastModifyUserId = '$userId', tLastModifyDate = '$time' where bDelete = 0 AND iDataType = 2 AND iSchoolId in ($existSchoolId)";
            $data = $this->db->execute($sql);
            if (!$data){
                return $this->sendErrorResponse(500, '保存失败');
            }
        }

        $needInsertArr = array_diff($schoolIdArr, $existRemarkData);
        if (!empty($needInsertArr)){
            $str ='';
            $sql = "INSERT INTO XHSys_DeviceCheck(iSchoolId,iDataType,sRemarkData,iCreateUserId,tCreateDate,iLastModifyUserId,tLastModifyDate) VALUES $str";
            foreach ($needInsertArr as $schoolId){
                $sql .= "($schoolId, 2, '$remark','$userId','$time','$userId','$time'),";
            }
            $data = $this->db->execute(trim($sql, ','));
            if (!$data){
                return $this->sendErrorResponse(500, '保存出错');
            }
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 设备审核历史列表页
     *
     * @return mixed
     *
     * create by qgz 20180508
     */
    public function checkListAction()
    {
        $this->view->setTemplateBefore('listForm');
        $schoolId = $this->request->getQuery('iSchoolId');
        if (!UserPower::checkUserPower('Device_CheckHistory')){
            return $this->sendViewError('无查看此页面权限');
        }
        $bar = [];
        if (!$schoolId){
            $listSearchArr[] = ['type' => 'text', 'id' => 'list_school', 'style' => 'width:100px;', 'label' => ' 学校: '];
            $bar = ['searchToolbar' => Template::createSearchToolBar($listSearchArr)];
        }
        Main::showNavPosition();
        Assets::easyUI('js/device/deviceCheck.js');
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHSys_CheckList', $bar),
        ]);
    }

    /**
     * 设备审核双击到领用页
     *
     * @return mixed
     *
     * create by qgz 20180531
     */
    public function deviceCheckListAction()
    {
        $schoolId = $this->request->getQuery('iSchoolId');
        $this->view->pick('device/checkHistory');
        if (!UserPower::checkUserPower('Device_Check')){
            return $this->sendViewError('无查看此页面权限');
        }
        return $this->view->setVars(['schoolId' => $schoolId]);
    }

    /**
     * 获取备用机和教师机列表
     *
     * @return mixed
     *
     * create by qgz 20180531
     */
    public function getRegisterListAction()
    {
        $this->view->setTemplateBefore('listForm');
        $type = $this->request->getQuery('type');
        Main::showNavPosition();
        Assets::easyUI('js/device/deviceCheckList.js');
        if (!UserPower::checkUserPower('Device_Check')){
            return $this->sendViewError('无查看此页面权限');
        }
        if ($type == 1) {
            $xmlName = 'XHSys_DeviceCheckList';
        } else if ($type == 2) {
            $xmlName = 'XHSys_DeviceCheckTea';
        } else {
            $xmlName = '';
        }
        return $this->view->setVars([
            'List' => Template::createList('list', $xmlName)
        ]);
    }

    /**
     * 获取审核历史列表数据
     *
     * @return mixed
     *
     * create by qgz 20180508
     */
    public function getCheckListAction()
    {
        $schoolInfo = $this->request->getPost('school');
        $iSchoolId = $this->request->getPost('iSchoolId');
        try {
            $parameters = [
                'columns' => 'iSchoolId, sSchoolName, iZyj, iByj, iGyj, iJsj, tCheckDate, sRemarkData',
                'conditions' => ' bDelete = 0 AND iDataType = 1 '
            ];
            if ($schoolInfo){
                $parameters['conditions'] .= " AND sSchoolName like '%{$schoolInfo}%' ";
            }
            if ($iSchoolId){
                $parameters['conditions'] .= " AND iSchoolId = $iSchoolId ";
            }
            $schoolPowerIds = User::getSchoolPower(false, null, true);
            if ($schoolPowerIds !== true) {
            	if (!empty($schoolPowerIds)){
		            $schoolPowerIds = implode(',', $schoolPowerIds);
		            $parameters['conditions'] .= " AND iSchoolId in ($schoolPowerIds)";
	            } else {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
	            }
            }
            $parameters['conditions'] .= 'ORDER BY iSchoolId desc, tCheckDate desc';
            $data = Main::runModelPage('Admin\Models\device\XhsysDevicecheck', $parameters);
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 维修申请--学生
     *
     * @return mixed
     *
     * create by qgz 20180522
     */
    public function showCreateAction(){
        Assets::select2();
        Assets::easyUI('js/device/showForm.js');
        $this->view->pick('device/showForm');

        $id = $this->request->getQuery('id');
        $schoolId = $this->request->getQuery('schoolId');
        $parameters = [
            'columns' => 'sLogonName, sModel, sDeviceNumber, sImei',
            'conditions' => ' bDelete = 0 and iUserId = :iUserId:',
            'bind' => ['iUserId' => $id]
        ];
        $data = XhsysAccountdevicelocked::findFirst($parameters);
        if (!$data){
            return $this->sendViewError('暂无设备数据');
        } else {
            $data = $data->toArray();
        }

        $userInfoArr = XhsysUser::findFirst([
            'columns' => 'sUserName, sMotherPhone, sFatherPhone, sOtherPhone',
            'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
            'bind' => ['iUserId' => $id]
        ]);
        if (!$userInfoArr){
            return $this->sendViewError('暂无该学生数据');
        }
        $userStud = XhsysUserstud::findFirst([
            'columns' => 'sMotherName, sFatherName, sOtherName',
            'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
            'bind' => ['iUserId' => $id]
        ]);
        //add father name
        $this->view->setVars([
            'id' => $id,
            'schoolId' => $schoolId,
            'sLogonName' => $data['sLogonName'],
            'sUserName' => $userInfoArr->sUserName,
            'sModel' => $data['sModel'],
            'sDeviceNumber' => $data['sDeviceNumber'],
            'sImei' => $data['sImei'],
            'fatherInfo' => ['name' => $userStud ? $userStud->sFatherName : '', 'phone' => $userInfoArr->sFatherPhone],
            'motherInfo' => ['name' => $userStud ? $userStud->sMotherName : '', 'phone' => $userInfoArr->sMotherPhone],
            'guardInfo' => ['name' => $userStud ? $userStud->sOtherName : '', 'phone' => $userInfoArr->sOtherPhone],
        ]);
    }

    /**
     * 获取维修项目枚举
     *
     * @return array
     *
     * create by qgz 20180621
     */
    public function getProjectEnum(){
        $data = XhsysDevicerepairProject::find([
            'columns' => 'sProjectName',
            'conditions' => 'bDelete = 0',
            'group' => 'sProjectName'
        ])->toArray();
        $data = array_column($data, 'sProjectName', 'sProjectName');
        return $data;
    }

    /**
     * 设备维修页
     *
     * @return mixed
     *
     * create by qgz 20180509
     */
    public function repairApplyAction(){
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::UMEditor();
        Assets::select2();
        Assets::importMainJs('assets/jquery/ajaxfileupload.js');
        Assets::importMainJs('assets/fileinput/fileinput.js');
        Assets::easyUI('js/device/repairApply.js');
        if (!UserPower::checkUserPower('Device_Repair')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        $enum = $this->registerEnum['progress'];
        $enum = ['' => '--状态--'] + $enum;
        $projectEnum = $this->getProjectEnum();
        $projectEnum = ['' => '--收费项目--'] + $projectEnum;
        $purposeEnum = ['' => '--用途--'] + $this->registerEnum['repairPurposeType'];
        $commitEnum = ['' => '--类型--', '0' => '先收后修', '1' => '先修后收'];
        $delayEnum = ['' => '--延时--'] + $this->delayStatus;
        $documentEnum = ['' => '--票据--', '1' => '无', '2' => '有'];
        $listSearchArr = $listButtonArr = [];
        $xmlName = 'XHSys_RepairApply';
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'progress_status', 'style' => 'width: 80px;', 'multiple' => true, 'data' => $enum];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'school_area', 'style' => 'width: 110px;'];
	    $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'repair_commit', 'style' => 'width: 70px;', 'data' => $commitEnum];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'repair_project', 'style' => 'width: 100px;', 'data' => $projectEnum];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'repair_purpose', 'style' => 'width: 70px;', 'data' => $purposeEnum];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'repair_delay', 'style' => 'width: 70px;', 'data' => $delayEnum];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'repair_document', 'style' => 'width: 70px;', 'data' => $documentEnum];
	    $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'repair_date', 'style' => 'width: 80px;'];
	    $listSearchArr[] = ['type' => 'text', 'id' => 'repair_startTime'];
	    $listSearchArr[] = ['type' => 'text', 'id' => 'repair_endTime', 'label' => ' ~ '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        $listSearchArr[] = ['type'=>'button', 'id'=>'bt_list_search', 'text' => '查找', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $listSearchArr[] = ['type'=>'button', 'id'=>'bt_list_export', 'text' => '导出', 'icon'=>'fa-file-excel-o', 'style'=>'margin-left:10px'];
        $power = [];
        $isRepairPerson = true;
        if (UserPower::checkUserPower('Device_Repair_Add')) {
            $power['apply'] = true;
            $isRepairPerson = false;
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'添加', 'plain'=>'true', 'icon'=>'fa-plus'];
        }
        if (UserPower::checkUserPower('Device_Repair_Del')){
            $isRepairPerson = false;
            $listButtonArr[] = ['id'=>'bt_list_delRepair', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }
        if (UserPower::checkUserPower('Device_Repair_Manage')) {
            $power['manage'] = true;
            $isRepairPerson = false;
            $listButtonArr[] = ['id'=>'bt_list_receive', 'text'=>'接收', 'plain'=>'true', 'icon'=>'fa-handshake-o'];
            $listButtonArr[] = ['id'=>'bt_list_goRepair', 'text'=>'送修', 'plain'=>'true', 'icon'=>'fa-location-arrow'];
        }
        if (UserPower::checkUserPower('Device_Repair_Repair')) {
            $power['repair'] = true;
            $listButtonArr[] = ['id' => 'bt_list_startCheck', 'text' => '开始检修', 'plain' => 'true', 'icon' => 'fa-wrench'];
            $listButtonArr[] = ['id' => 'bt_list_checkResult', 'class' => 'menubutton', 'text' => '检测结果', 'plain' => 'true', 'icon' => 'fa-print'];
            $listButtonArr[] = ['id' => 'bt_list_startRepair', 'text' => '开始维修', 'plain' => 'true', 'icon' => 'fa-hourglass-half'];
            $listButtonArr[] = ['id' => 'bt_list_endRepair', 'text' => '维修完成', 'plain' => 'true', 'icon' => 'fa-flag-o'];
        }
        if (UserPower::checkUserPower('Device_Repair_Service')) {
            $isRepairPerson = false;
	        $power['server'] = true;
            $listButtonArr[] = ['id' => 'bt_list_checkPay', 'class' => 'menubutton', 'text' => '收费沟通', 'plain' => 'true', 'icon' => 'fa-dollar'];
	        $listButtonArr[] = ['id' => 'bt_list_communication', 'class' => 'menubutton', 'text' => '沟通', 'plain' => 'true', 'icon' => 'fa-commenting-o'];
        }
        if (Power::exist('Device_Repair_Commit') && !Power::exist('Device_Repair_Service')){
	        $isRepairPerson = false;
	        $power['commit'] = true;
	        $listButtonArr[] = ['id' => 'bt_list_communication', 'class' => 'menubutton', 'text' => '沟通', 'plain' => 'true', 'icon' => 'fa-commenting-o'];
        }
        if (UserPower::checkUserPower('Device_Repair_Manage')){
            $isRepairPerson = false;
            $listButtonArr[] = ['id' => 'bt_list_confirmPay', 'text' => '收费确认', 'plain' => 'true', 'icon' => 'fa-check'];
        }
        if (UserPower::checkUserPower('Device_Repair_Repair')) {
            $listButtonArr[] = ['id'=>'bt_list_sendBack', 'text'=>'寄回', 'plain'=>'true', 'icon'=>'fa-truck'];
        }
        if (UserPower::checkUserPower('Device_Repair_Manage')) {
            $isRepairPerson = false;
            $listButtonArr[] = ['id'=>'bt_list_takeAway', 'text'=>'领取', 'plain'=>'true', 'icon'=>'fa-blind'];
        }
        $listButtonArr[] = ['id' => 'bt_list_repairResult', 'class' => 'menubutton', 'text' => '维修结果', 'plain' => 'true', 'icon' => 'fa-plug'];
        if (UserPower::checkUserPower('Device_Repair_History')){
            $isRepairPerson = false;
            $listButtonArr[] = ['id'=>'bt_list_history', 'text'=>'流程记录', 'plain'=>'true', 'icon'=>'fa-eye'];
        }
        $listButtonArr[] = ['id' => 'bt_list_delay', 'text' => '延时记录', 'plain' => 'true', 'icon' => 'fa-random'];
        $listButtonArr[] = ['id' => 'bt_list_stat', 'class' => 'menubutton', 'text' => '统计', 'plain' => 'true', 'icon' => 'fa-bar-chart'];
        if ($isRepairPerson && !User::isAdmin() && UserPower::checkUserPower('Device_Repair_Repair')){//仅为维修人员展示不同
            $xmlName = 'XHSys_RepairApplySpecial';
        }
        if (Power::exist('Device_Repair_ChangeStatus')){
	        $listButtonArr[] = ['id'=>'bt_list_changeStatus', 'text'=>'修改状态', 'plain'=>'true', 'icon'=>'fa-recycle'];
        }
	    if (Power::exist('Device_Repair_UploadDoc')){
		    $listButtonArr[] = ['id'=>'bt_list_uploadDoc', 'text'=>'上传单据', 'plain'=>'true', 'icon'=>'fa-upload'];
	    }
        return $this->view->setVars([
            'List'          => Template::createList('list', $xmlName, [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'power'         => $power
        ]);
    }

    /**
     * 添加设备维修--维修页
     *
     *
     * create by qgz 20180611
     */
    public function addDeviceRepairAction(){
        Assets::select2();
        Assets::easyUI('js/device/addDeviceRepair.js');
        $this->view->pick('device/addDeviceRepairForm');
        $params = ['type' => 3];//直接创建
        $this->view->setVars($params);
    }

    /**
     * 获取学校列表数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180611
     */
    public function getSchoolListDataAction(){
        $parameters = [
            'columns'    => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete = 0 AND (iStatus = 1 OR iStatus = 2) '
        ];
        $return = [];
        $data = XhschoolInfo::find($parameters)->toArray();
        if ($data){
            foreach ($data as $value){
                $return[] = ['id' => $value['iSchoolId'], 'text' => $value['sSchoolName']];
            }
        } else {
            return $this->sendErrorResponse(500, '暂无学校数据');
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 根据学校id获取用户列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180611
     */
    public function getUserListDataAction(){
        $return = [];
        $schoolId = $this->request->getPost('schoolId');
        if (!$schoolId){
            return $this->sendJsonResponse($return);
        }
        $parameters = [
            'columns'    => 'iUserId,sUserName',
            'conditions' => "bDelete = 0 AND iSchoolId =  $schoolId "
        ];
        $data = XhsysUser::find($parameters)->toArray();
        if (!empty($data)){
            foreach ($data as $value){
                $return[] = ['id' => $value['iUserId'], 'text' => $value['sUserName']];
            }
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 获取地域信息
     *
     * @return mixed
     *
     * create by qgz 20180604
     */
    public function getDepDataAction(){
        try {
            $data  = Hrm::getDepArray('XHYYB', 2, true);
            Tool::replaceKey($data, ['child' => 'children']);
            array_unshift($data, ['id' => '', 'text' => '--选择区域--', 'children' => []]);
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 上传检测报告
     *
     * @return mixed
     *
     * create by qgz 20180529
     */
    public function updateCheckFileAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '缺少文件');
        }
        $file = $this->request->getUploadedFiles()[0];
        if (!in_array(strtolower($file->getExtension()), ['jpg', 'jpeg', 'bmp', 'gif', 'png'])) {
            return $this->sendErrorResponse(400, '文件类型不正确');
        }
        // $filePath = Tool::buildPath(Main::getConfigByName('fileSave')['temp'], $file->getName());
        $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
        $filePath = TEMP_PATH . '/'.$fileName;
        $file->moveTo($filePath);
        $url = Main::uploadToFileManageSystem($filePath, 'img', null, true);
        if (!$url) {
            return $this->sendErrorResponse(500, '文件上传失败');
        } else {
            return $this->sendSuccessResponse($url);
        }
    }

	/**
	 * 单独上传单据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180718
	 */
    public function modifyDocUrlAction(){
    	$id = $this->request->getPost('id');
	    $docUrl = $this->request->getPost('docUrl');
	    if (!$id){
	    	return $this->sendErrorResponse(400, '请选择后操作');
	    }
	    if (!$docUrl){
		    return $this->sendErrorResponse(400, '未上传或等待上传完成后再操作');
	    }
	    $data = XhsysDevicerepair::findFirst(['conditions' => 'bDelete = 0 AND iChargeType != 0 AND iId = :iId:', 'bind' => ['iId' => $id]]);
	    if (!$data){
		    return $this->sendErrorResponse(500, '该记录不符合上传条件，请重新选择操作');
	    }
	    $data->sDocument = $docUrl;
	    if (!$data->save()){
		    return $this->sendErrorResponse(500, '操作失败');
	    }
	    return $this->sendSuccessResponse('成功');
    }

    /**
     * 获取设备检修数据列表
     *
     * @param bool $return
     * @return mixed
     *
     * create by qgz 20180510
     * modify by qgz 20180524 增加备用自用类型
     * modify by qgz 20180604 展示父母名和电话
     * modify by qgz 20180621 增加收费项目和创建人搜索
     */
    public function getRepairDataAction($return=false){
        $status = $this->request->get('search');
        $progress_status = $this->request->get('progress_status');
        $school_area = $this->request->get('school_area');
        $repair_project = $this->request->get('repair_project');
        $repair_purpose = $this->request->get('repair_purpose');
        $repair_delay = $this->request->get('repair_delay');
	    $repair_commit = $this->request->get('repair_commit');
	    $repair_date = $this->request->get('repair_date');
	    $startTime = $this->request->get('startTime');
	    $endTime = $this->request->get('endTime');
        $document = $this->request->get('document');
        $iIds = $this->request->get('iIds');
        $export = $this->request->get('export');//是否是导出
	    $sort = $this->request->get('sort');
	    $order = $this->request->get('order');
        if ($export == 'true'){
            if ($progress_status){
                $progress_status = array_filter(explode(',', $progress_status));
            }
            $status = ['vague' => ''];
        }

        $parameters = [
            'columns' => '*',
            'conditions' => ' bDelete = 0 ',
            'order' => 'tCreateDate DESC',
//            'order' => 'tLastModifyDate DESC',
        ];
        if ($sort && $order){
	        $parameters['order'] = "{$sort} {$order}";
        }
        $enumArr = $this->registerEnum['progress'];
        $fina_status = [];
        if (!empty($progress_status)){
            if (in_array('', $progress_status) && count($progress_status) == 1){
                $fina_status = [];
            } elseif (in_array('', $progress_status) && count($progress_status) > 1){
                $fina_status = array_diff($progress_status, ['']);
                $fina_status = implode(',', $fina_status);
            } elseif (!in_array('', $progress_status)){
                $fina_status = implode(',', $progress_status);
            }
        }
        if (count($fina_status) > 0){
            $parameters['conditions'] .= " and iStatus in ($fina_status)";
        }

	    try {
		    if (!empty($school_area)){
			    $depId  = $school_area;
			    $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
			    $authId = $staff['iUserId'];
			    if (!$authId) {
				    return $this->sendErrorResponse(500, '找不到该部门负责人');
			    }
			    $schoolArr = User::getSchool(true, $authId, true);
			    if (!empty($schoolArr)){
				    $schoolIds = implode(',', array_keys($schoolArr));
				    $parameters['conditions'] .= " and iSchoolId in ($schoolIds)";
			    }
		    }
		    if ($repair_project){
			    $parameters['conditions'] .= " and sRepairProjectName like '%{$repair_project}%' ";
		    }
		    if ($repair_purpose){
			    $parameters['conditions'] .= " and iPurposeType = '{$repair_purpose}' ";
		    }
		    if ($repair_commit != ''){
			    $parameters['conditions'] .= " and iChargeType = '{$repair_commit}' ";
		    }
		    $otherParams = [];
		    $isRepair = UserPower::checkUserPower('Device_Repair_Repair');//维修人员
            $isServer = UserPower::checkUserPower('Device_Repair_Service');//客服
		    if ($status['vague'] && (User::isAdmin() || !$isRepair || $isServer)) {//维修人员不展示创建人，不搜索
			    $userIdArr = User::searchUser($status['vague']);
			    if (!empty($userIdArr)){
				    $userIdArr = implode("','", $userIdArr);
				    $otherParams = [" iCreateUserId in ('" . $userIdArr . "')"];//OR的关系
			    }
		    }
		    if ($iIds){
			    $parameters['conditions'] .= " and iId in ($iIds)";
		    }

		    $userId = User::getId();
		    $schoolPowerIds = User::getSchoolPower(false, null, true);
		    if ($schoolPowerIds !== true){
			    if (!empty($schoolPowerIds)){
				    $schoolPowerIds = implode(',', $schoolPowerIds);
				    $parameters['conditions'] .= " and ( iSchoolId in ($schoolPowerIds) or ((iSchoolId is null or iSchoolId = 0) and iCreateUserId = $userId ))";
			    } else {
				    $parameters['conditions'] .= " AND (iSchoolId is null or iSchoolId = 0) and iCreateUserId = $userId";//没有学校id的，创建者可查看
			    }
		    }

		    //获取供应商权限
		    $coopData = Coop::getPower('devRepair');//true or [] or ['a','b'..]
		    if ($coopData !== true){
			    $returnData = ['total' => 0, 'rows' => []];
		    	if (!empty($coopData)){
				    $produceArr = Coop::getProduce($coopData, $withName = true);
				    if ($produceArr){
					    foreach ($produceArr as &$produce){
						    $produce = trim($produce);
					    }
					    unset($produce);
					    $produceArr = implode("','", $produceArr);
					    $parameters['conditions'] .= " and sModel in ('" . $produceArr . "')";
				    } else {
					    return $this->sendJsonResponse($returnData);
				    }
			    } else {
				    return $this->sendJsonResponse($returnData);
			    }
		    }
		    if ($status['vague']){//搜索学校
			    $machId = School::searchSchool($status['vague']);
			    if (!empty($machId)){
				    $machId = implode(',', $machId);
				    $otherParams[] = " iSchoolId in ($machId) ";
			    }
		    }
		    if ($export != 'true'){
			    $enum = $this->addColorShow($enumArr);
		    }else{
			    $enum = $enumArr;
		    }
		    if ($repair_date === '0' || $repair_date == '1' || $repair_date == '2'){//送修\寄回时间或最后沟通时间
			    $dateStr = $repair_date === '0' ? 'sRepairDate' : ($repair_date === '1' ? 'tLatestCommDate' : 'sExpBackDate');
			    if ($startTime){
				    $parameters['conditions'] .= " AND ".$dateStr." >= '{$startTime}'";
			    }
			    if ($endTime){
				    $parameters['conditions'] .= " AND ".$dateStr." <= '{$endTime}"." 23:59:59"."'";
			    }
		    }
		    if ($repair_delay) {//延时筛选
		        $delayId = XhsysDevicerepairDelay::find([
		            'conditions' => 'bDelete = 0 and iDelayStatus = 1 and iProgressStatus = :iProgressStatus:',
                    'bind' => ['iProgressStatus' => $repair_delay]
                ])->toArray();
		        if ($delayId) {
		            $repairApplyId = array_values(array_unique(array_column($delayId, 'iRepairApplyId')));
		            if ($repairApplyId) {
                        $repairApplyId = implode(',', $repairApplyId);
                        $parameters['conditions'] .=  " AND iId in ($repairApplyId) ";
                    }
                } else {
		            return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                }
            }
            //是否有票据
            if ($document == 1) {
                $parameters['conditions'] .= " AND (sDocument = '' OR sDocument IS NULL) ";
            } else if($document == 2) {
                $parameters['conditions'] .= " AND sDocument != '' AND sDocument IS NOT NULL ";
            }
		    Main::runSearchVagueConditions($parameters['conditions'], ['sUserName', 'sLogonName', 'sModel', 'sDeviceNumber', 'sImei', 'sBrand'], [], $otherParams);
		    $data = Main::runModelPage('Admin\Models\device\XhsysDevicerepair', $parameters,
			    ['iStatus' => $enum, 'iDestination' => $this->registerEnum['destination'],
			     'iCheckResult' => $this->registerEnum['checkResult'], 'iAgreeCharge' => $this->registerEnum['agreeCharge'],
			     'iRenewal' => $this->registerEnum['renewal'], 'iConfirmCharge' => $this->registerEnum['iConfirmCharge'], 'iCreateType' => $this->registerEnum['iCreateType'],
			     'iPurposeType' => $this->registerEnum['repairPurposeType']]);
		    if ($data['total'] != 0){
                Main::addUserGradeById($data['rows'], ['iUserId' => 'iGradeCode'], true);
		        Main::addUserClassById($data['rows'], ['iUserId' => 'sAdClsName']);
			    $data = $this->addProgress($data, $enumArr, $export);
			    //替换用户名为小写
			    foreach ($data['rows'] as $index => $row) {
				    $data['rows'][$index]['sLogonName'] = strtolower($row['sLogonName']);
				    if ($row['iUserId']) {
                        $row['iGradeCode'] = isset($row['iGradeCode']) ? $row['iGradeCode'] : '';
                        $row['sAdClsName'] = isset($row['sAdClsName']) ? $row['sAdClsName'] : '';
                        $data['rows'][$index]['gradeClass'] = $row['iGradeCode'] . $row['sAdClsName'];
                    }
			    }

			    //绑定上报设备
			    $rows       = array_column($data['rows'], null, 'sLogonName');
			    $accounts   = array_values(array_filter(array_keys($rows)));
			    if (!empty($accounts)) {
				    $deviceInfo = XhsysUsertablet::find([
					    'columns'    => 'iUTId,sNowReceiverAccount,iReceivePurpose,sDevNumber,sDevType,sMacAddress,tCreateDate',
					    'conditions' => 'bDelete = 0 AND bDone = 0 AND sNowReceiverAccount IN ({accounts:array})',
					    'bind'       => ['accounts' => $accounts]
				    ])->toArray();
				    $receiverAccount = [];
				    if (!empty($deviceInfo)){
					    $receiverAccount = array_column($deviceInfo, null, 'sNowReceiverAccount');
				    }
			    }
			    //绑定借用
			    $rows    = array_column($data['rows'], null, 'iUserId');
			    $userIds = array_values(array_filter(array_keys($rows)));
			    if (!empty($userIds)) {
				    $borrowInfo = XhsysAccountdevicelocked::find([
					    'columns'    => 'iUserId,iADLId,sDeviceNumber,sIP,sMac,sModel,sImei,tCreateDate',
					    'conditions' => "bDelete = 0 AND iSourceType = 2 AND iUserId IN ({studIds:array})",
					    'bind'       => ['studIds' => $userIds]
				    ])->toArray();
				    $idAccount = [];
				    if (!empty($borrowInfo)) {
					    $idAccount = array_column($borrowInfo, null, 'iUserId');
				    }
			    }
			    $parentPhoneInfo = $parentNameInfo = [];
			    if (!empty($userIds)) {
				    $parentPhoneInfo = XhsysUser::find([
					    'columns' => 'iUserId, sUserName, sMotherPhone, sFatherPhone, sOtherPhone',
					    'conditions' => "bDelete = 0 and iUserId IN ({iUserId:array})",
					    'bind' => ['iUserId' => $userIds]
				    ])->toArray();

				    $parentNameInfo = XhsysUserstud::find([
					    'columns' => 'iUserId, sMotherName, sFatherName, sOtherName',
					    'conditions' => "bDelete = 0 and iUserId IN ({iUserId:array})",
					    'bind' => ['iUserId' => $userIds]
				    ])->toArray();
			    }

			    $parentPhoneInfo = array_column($parentPhoneInfo, null, 'iUserId');
			    if (!empty($parentNameInfo)){
				    $parentNameInfo = array_column($parentNameInfo, null, 'iUserId');
			    }
			    foreach ($parentPhoneInfo as $key => &$val){
				    if (isset($parentNameInfo[$key])){
					    $val['sMotherName'] = $parentNameInfo[$key]['sMotherName'];
					    $val['sFatherName'] = $parentNameInfo[$key]['sFatherName'];
					    $val['sOtherName'] = $parentNameInfo[$key]['sOtherName'];
				    }else{
					    $val['sMotherName'] = $val['sFatherName'] = $val['sOtherName'] = null;
				    }
			    }
			    unset($parentNameInfo);

			    foreach ($data['rows'] as &$value){
				    $value['iAgreeChargeName'] = $value['iAgreeCharge'];
				    if (isset($receiverAccount[$value['sLogonName']])){
					    $value['iReceivePurpose'] = $receiverAccount[$value['sLogonName']]['iReceivePurpose'] ? '备用' : '自用';
				    }
				    if (isset($idAccount[$value['iUserId']])){
					    $value['iReceivePurpose'] = '借用';
				    }

				    if ($value['iCheckResult'] == '无法检修'){
					    $value['iCheckResult'] .= '：' . $value['sUnRepairReason'];
					    $value['iConfirmCharge'] = '';
				    } elseif ($value['iCheckResult'] == '收费'){
					    if ($value['iAgreeCharge'] == '不同意'){
						    $value['iAgreeCharge'] = '('.$value['iAgreeCharge'].')沟通内容/原因：' . $value['sDisagreeReason'];
					    } elseif ($value['iAgreeCharge'] == '同意') {
						    $value['iAgreeCharge'] = '('.$value['iAgreeCharge'].')沟通内容：' . $value['sDisagreeReason'];
					    } else {
						    $value['iAgreeCharge'] = '';
					    }
				    } elseif ($value['iCheckResult'] == '免费'){
					    $value['iAgreeCharge'] = '无需收费';
					    $value['iConfirmCharge'] = '无需确认';
				    } else {
					    $value['iConfirmCharge'] = '';
				    }
				    if ($value['sRepairContent']){
					    if ($value['iRenewal'] == '是'){
						    $value['iRenewal'] = '（变化信息）';
						    if ($value['sNewDeviceNumber']){
							    $value['iRenewal'] .= '新设备号：' . $value['sNewDeviceNumber'] . '；';
							    $value['iRenewal'] .= '新Imei：' . $value['sNewImei'] . '；';
						    }
						    if ($value['sNewMessage']){
							    $value['iRenewal'] .= '其他：' . $value['sNewMessage'];
						    }
					    }
				    } else {
					    $value['iRenewal'] = '';
				    }
				    if ($value['sCheckReport']){
					    $value['sCheckReport'] = '<div><a reportUrl="'.$value['sCheckReport'].'" '.' class="checkReport">点击查看</a></div>';
				    }
				    if ($value['sDocument']){
					    $value['sDocument'] = '<div><a documentUrl="'.$value['sDocument'].'" '.' class="document">点击查看</a></div>';
				    }
				    $contact = '';
				    if (isset($parentPhoneInfo[$value['iUserId']])){
					    if ($parentPhoneInfo[$value['iUserId']]['sMotherName'] && $parentPhoneInfo[$value['iUserId']]['sMotherPhone']){
						    $contact .= '[妈妈]' . $parentPhoneInfo[$value['iUserId']]['sMotherName'] . '：' . $parentPhoneInfo[$value['iUserId']]['sMotherPhone'] . ';';
					    }
					    if ($parentPhoneInfo[$value['iUserId']]['sFatherName'] && $parentPhoneInfo[$value['iUserId']]['sFatherPhone']){
						    $contact .= '[爸爸]' . $parentPhoneInfo[$value['iUserId']]['sFatherName'] . '：' . $parentPhoneInfo[$value['iUserId']]['sFatherPhone'] . ';';
					    }
					    if ($parentPhoneInfo[$value['iUserId']]['sOtherName'] && $parentPhoneInfo[$value['iUserId']]['sOtherPhone']){
						    $contact .= '[监护人]' . $parentPhoneInfo[$value['iUserId']]['sOtherName'] . '：' . $parentPhoneInfo[$value['iUserId']]['sOtherPhone'] . ';';
					    }
				    }
				    $value['contact'] = $contact;
			    }
			    Main::runUserNameById($data['rows'], 'iCreateUserId', true);
			    Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
			    unset($value);
			    if ($return){
				    return $data['rows'];
			    }
		    }
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500, $e->getMessage());
	    }
        return $this->sendJsonResponse($data);
    }

    /**
     * 添加颜色
     *
     * @return mixed
     *
     * create by qgz 20180516
     */
    public function addColorShow($enum){
        foreach ($enum as &$value){
            switch ($value){
                case '未开始' : $value = '<div style="background-color: darkgray">'.$value.'</div>'; break;
                case '无法维修待寄回' : $value = '<div style="background-color: #FFFF00">'.$value.'</div>'; break;
                case '不同意收费待寄回' : $value = '<div style="background-color: #FFA800">'.$value.'</div>'; break;
                case '已领取' : $value = '<div style="background-color: green;color: white"">'.$value.'</div>'; break;
                case '正常开机' : $value = '<div style="background-color: green;color: white"">'.$value.'</div>'; break;
                case '未维修' : $value = '<div style="background-color: #FFA300;color: white">'.$value.',已结束'.'</div>'; break;
                case '返回重修' : $value = '<div style="background-color: red;color: white">'.$value.'</div>'; break;
                default:$value = '<div style="background-color: #00F1FA">'.$value.'</div>';break;
            }
        }
        return $enum;
    }

    /**
     * 添加title进程
     *
     * @return mixed
     *
     * create by qgz 20180516
     */
    public function addProgress($data, $enum, $export){
        foreach ($data['rows'] as &$rows){
	        $rows['iStatusName'] = $rows['iStatus'];
	        $rows['showUserName'] = $rows['sUserName'];
            $rows['showProjectName'] = $rows['sRepairProjectName'];
            if ($rows['sHandleProgress'] === '0'){
                $rows['iStatus'] = str_replace('<div style=', '<div title="未开始" style=', $rows['iStatus']);
            }else{
                $arr = explode(',', $rows['sHandleProgress']);
                foreach ($arr as $key => &$progress){
                    if (isset($enum[$progress])) {
                        $arr[$key] = $enum[$progress];
                    }
                }
                unset($progress);
                $arr = implode('->', $arr);
                $rows['iStatus'] = str_replace('<div style=', '<div title="'.'流程：'.$arr.'" style=', $rows['iStatus']);
                unset($arr);
            }
            if ($rows['sExpressSend']){
                $rows['sExpressSend'] = '('.$rows['sExpSendCompany'].')'.$rows['sExpressSend'];
            }
            if ($rows['sExpressReceive']){
                $rows['sExpressReceive'] = '('.$rows['sExpBackCompany'].')'.$rows['sExpressReceive'];
            }
            if ($rows['sRemark'] && $export != 'true'){
                $rows['sRemark'] = '<div style="cursor:pointer" title="点击查看详情" class="sRemark" sRemark="'.$rows['sRemark'].'" '.'><a>'.$rows['sRemark'].'</a></div>';
            }
            if ($rows['showProjectName'] && $rows['bProjectChange'] == 1){
	            $rows['showProjectName'] = "<i title='维修项目已发生变化，请确认' class='fa fa-exclamation-triangle' style='color:red;'></i>  ".$rows['showProjectName'];
            }
            if ($rows['iChargeType'] == 1 && !Power::exist('Device_Repair_Repair')){//维修人员不可见
	            $rows['showUserName'] = "<i title='设备正在维修但未确认收费，请确认' class='fa fa-question-circle' style='color:red;'></i>  ".$rows['showUserName'];
            }
            if ($rows['iDelayStatus']) {//添加延时
                $title = $this->delayStatus;
                $rows['showUserName'] .= "&nbsp<i title='" . $title[$rows['iDelayStatus']] . "已延时' class='fa fa-hourglass-half' style='color:red;'></i>  ";
            }
        }
        unset($rows);
        return $data;
    }

    /**
     * 创建设备维修数据
     *
     * @return mixed
     *
     * create by qgz 20180509
     */
    public function saveRepairDataAction(){
        $data = $this->request->getPost();
        if (!$data['sModel'] || !$data['sDeviceNumber'] || !$data['sBrand'] || !$data['iDestination'] || !$data['remark'] ||
            ($data['iDestination'] == 2 && (!$data['expressSend'] || !$data['expressCompany']))) {
            return $this->sendErrorResponse(400, '请填写完整信息');
        }
        $params = [
            'columns' => 'iStatus',
            'conditions' => "sModel = :sModel: AND sDeviceNumber = :sDeviceNumber: AND sBrand = :sBrand: AND bDelete = 0 ",
            "order" => "tCreateDate DESC",
            'bind' => ['sModel' => $data['sModel'], 'sDeviceNumber' => $data['sDeviceNumber'], 'sBrand' => $data['sBrand']]
        ];
        if ($data['userId']){
            $params['conditions'] .= " AND iUserId = :userid: ";
            $params['bind']['userid'] = $data['userId'];
        }
        $findData = XhsysDevicerepair::findFirst($params);
        $enum = $this->registerEnum['progress'];
        $progress = array_flip($enum);
        if ($findData){
            if ($findData->iStatus != $progress['正常开机'] && $findData->iStatus != $progress['未维修']){
                return $this->sendErrorResponse(400, '该设备已在申请维修中');
            }
        }
        $userName = $data['userName'];
        $userLogOnName = $data['logonName'];
        $this->db->begin();
        if ($data['userId']){
            $userInfo = XhsysUser::findFirst([
                'columns' => '*',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind' => ['iUserId' => $data['userId']]
            ]);
            if (!$userInfo){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '暂无该学生数据');
            }
            if ($data['type'] != 2 && $data['type'] != 3){//创建类型，默认1学生2领用列表3设备维修
                $userStud = XhsysUserstud::findFirst([
                    'columns' => '*',
                    'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                    'bind' => ['iUserId' => $data['userId']]
                ]);
                if (!$userStud){
                    $userStud = new XhsysUserstud();
                    $userStud->iUserId = $data['userId'];
                }
                //存父母姓名
                $userStud->sMotherName = $data['motherName'];
                $userStud->sFatherName = $data['fatherName'];
                $userStud->sOtherName = $data['guardName'];
                if (!$userStud->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存家长姓名出错');
                }
                //存父母电话
                $userInfo->sMotherPhone = $data['motherPhone'];
                $userInfo->sFatherPhone = $data['fatherPhone'];
                $userInfo->sOtherPhone = $data['guardPhone'];
                if (!$userInfo->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存电话信息出错');
                }
            }
            $userName = $userInfo->sUserName;
            $userLogOnName = $userInfo->sLogonName;
        }
        $XhsysDevicerepair = new XhsysDevicerepair();
        $XhsysDevicerepair->iUserId = $data['userId'];
        $XhsysDevicerepair->iSchoolId = $data['schoolId'];
        $XhsysDevicerepair->sUserName = $userName;
        $XhsysDevicerepair->sLogonName = $userLogOnName;
        $XhsysDevicerepair->sModel = $data['sModel'];
        $XhsysDevicerepair->sDeviceNumber = $data['sDeviceNumber'];
        $XhsysDevicerepair->sImei = $data['sImei'];
        $XhsysDevicerepair->sBrand = $data['sBrand'];
        if ($data['iDestination'] == 2){//检修站时状态直接为送修中
            $XhsysDevicerepair->sRepairDate = $data['repairDate'];
            $XhsysDevicerepair->iStatus = $progress['送修中'];
            $XhsysDevicerepair->sHandleProgress = $progress['未开始'].','.$progress['已接收'].','.$progress['送修中'];
            $XhsysDevicerepair->sExpSendCompany = $data['expressCompany'];
            $XhsysDevicerepair->sExpressSend = $data['expressSend'];
        }
        $XhsysDevicerepair->iPurposeType = $data['purpose'];
        $XhsysDevicerepair->sProduct = $data['purpose'] == 6 && isset($data['product']) ? $data['product'] : '';
        $XhsysDevicerepair->iDestination = $data['iDestination'];
        $XhsysDevicerepair->sRemark = $data['remark'];
        $XhsysDevicerepair->iCreateType = $data['type'] ? $data['type'] : 1 ;//创建类型，默认1学生2领用列表3设备维修
        if (!$XhsysDevicerepair->save()){
            $this->db->rollback();
            return $this->sendErrorResponse(500, '保存出错');
        }
        //若用途是库存机且是维修站，设备出库
        if ($data['purpose'] == 6 && $data['iDestination'] == 2 && isset($data['product']) && $data['product']){
            try{
//                Ims::resOut(['iProdId' => $data['product'], 'iOutNum' => 1], [], '设备维修出库', User::getId());
                Ims::prodOut(['iProdId' => $data['product'], 'iOutNum' => 1, 'iOutType' => 4], [], '设备维修出库', User::getId());
            } catch (\Exception $e){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '出库错误：' . $e->getMessage());
            }
        }
        $this->db->commit();
        return $this->sendSuccessResponse('成功');
    }


    /**
     * 取消设备维修
     *
     * @return mixed
     *
     * create by qgz 20180509
     */
    public function delRepairDataAction(){
        $id = $this->request->getPost('id');
        if (empty($id)){
            return $this->sendErrorResponse(400, '参数错误');
        }
        $parameters = [
            'columns' => 'sModel, sDeviceNumber',
            'conditions' => ' bDelete = 0 and iUserId = :iUserId:',
            'bind' => ['iUserId' => $id[0]]
        ];
        $data = XhsysAccountdevicelocked::findFirst($parameters)->toArray();
        if (empty($data)){
            return $this->sendErrorResponse(500, '无设备数据');
        }
        $params = [
            'columns' => '*',
            'conditions' => "iUserId = :userid: AND sModel = :sModel: AND sDeviceNumber = :sDeviceNumber: AND bDelete = 0",
            'bind' => ['userid' => $id[0], 'sModel' => $data['sModel'], 'sDeviceNumber' => $data['sDeviceNumber']]
        ];
        $findData = XhsysDevicerepair::findFirst($params);
        if ($findData){
            $enum = $this->registerEnum['progress'];
            $progress = array_flip($enum);
            if ($findData->iStatus != $progress['未开始'] && $findData->iStatus != $progress['已接收']){
                return $this->sendErrorResponse(500, '该用户的设备检修流程已开始或已完成，无法取消');
            }
            $findData->bDelete = 1;
            if (!$findData->save()){
                return $this->sendErrorResponse(500, '取消出错');
            }
            return $this->sendSuccessResponse('成功');
        }else{
            return $this->sendErrorResponse(500, '没有该维修申请数据');
        }

    }

    /**
     * 删除设备维修数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180621
     */
    public function delRepairApplyAction(){
        $id = $this->request->getPost('ids');
        if (empty($id)){
            return $this->sendErrorResponse(400, '参数错误');
        }
        $ids = implode(',', $id);
        $sql = "update XHSys_DeviceRepair set bDelete = 1 where bDelete = 0 AND iId in ({$ids})";
        $data = $this->db->execute($sql);
        if (!$data){
            return $this->sendErrorResponse(500, '删除失败');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 生成二维码，type：1接收，2领取
     *
     * @return mixed
     *
     * create by qgz 20180601
     */
    public function getQRAction()
    {
        $ids = $this->request->getPost('ids');
        $type = $this->request->getPost('type');
        $status = $this->request->getPost('status');
        if (!$ids) {
            return $this->sendErrorResponse(400, '请选择后操作');
        }
        try {
            //判断该操作是否合法
            $enum = $this->registerEnum['progress'];
            $ids = is_array($ids) ? $ids : (array)$ids;
            $ok = $this->checkProgress($type, $status, $ids, $enum);
            if ($ok['type'] !== 0){
                return $this->sendErrorResponse(400, $ok['msg']);
            }
//            ob_start();
//            QRcode::png(
//                Tool::buildUrl('Device/changeStatus', ['ids' => $ids, 'type' => $type, 'status' => $status, 'needCreater' => 1]),
//                false, 0, 10, 1
//            );
//            $imgString = base64_encode(ob_get_contents());
//            ob_end_clean();
            return $this->sendSuccessResponse((new QrCode(Tool::buildUrl('Device/changeStatus', ['ids' => $ids, 'type' => $type, 'status' => $status, 'needCreater' => 1])))->writeDataUri(), false);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    public function receiveDeviceAction(){
        return $this->sendViewSuccess('已接收');
    }

    /**
     * 改变维修进程状态
     *
     * @return mixed
     *
     * create by qgz 20180511
     * modify by qgz 20180622 管理员可操作所有类型
     */
    public function changeStatusAction(){
        $type = $this->request->getPost('type');//操作进入状态的类型
        $status = $this->request->getPost('status');//点击按钮的类型
        $idArr = $this->request->getPost('ids');
        $sendCompany = $this->request->getPost('sendCompany');//寄出快递公司
        $sendExpress = $this->request->getPost('sendExpress');//寄出快递单号
        $unrepairresion = $this->request->getPost('unrepairresion');//无法维修原因
        $money = $this->request->getPost('money');//金额
        $backresion = $this->request->getPost('backresion');//沟通内容&不同意收费原因
        $express = $this->request->getPost('express');//寄回快递号
        $backExpCompany = $this->request->getPost('backExpCompany');//寄回快递公司
        $backexpress = $this->request->getPost('backexpress');//返回重修的快递号，如果有
        $backexpressCompany = $this->request->getPost('backExpressCom');//返回重修的快递公司，如果有
        $backdest = $this->request->getPost('backdest');//返回重修的去向，公司或检修站
        $backremark = $this->request->getPost('backremark');//返回重修故障描述
        $chectContent = $this->request->getPost('chectContent');//检测内容
        $repairContent = $this->request->getPost('repairContent');//维修内容
        $project = $this->request->getPost('project');//维修项目
        $newMessage = $this->request->getPost('newMessage');//维修后改变的内容
        $newDeviceNumber = $this->request->getPost('newDeviceNumber');//新设备号
        $newImei = $this->request->getPost('newImei');//新Imei
        $sRepairDate = $this->request->getPost('sRepairDate');//送修日期
        $checkReport = $this->request->getPost('checkReport');//检测报告url
        $document = $this->request->getPost('document');//收费单据url
        $expressCharge = $this->request->getPost('expressCharge');//运费
        $needCreater = $this->request->getQuery('needCreater');//是否需要创建者权限
        $commDate = $this->request->getPost('commDate');//交流沟通时间
        $backDate = $this->request->getPost('backDate');//寄回日期

        if (empty($type)){
            $type = $this->request->getQuery('type');
        }
        if (empty($status)){
            $status = $this->request->getQuery('status');
        }
        $enum = $this->registerEnum['progress'];
	    $progress = array_flip($enum);
        if (!in_array($type, array_keys($enum))){
            return $this->sendErrorResponse(400, '操作类型不存在');
        };
        if (empty($idArr)){
            $idArr = $this->request->getQuery('ids');
            if (empty($idArr)){
                return $this->sendErrorResponse(400, '请选择后操作');
            }
        }

        $idArr = is_array($idArr) ? $idArr : (array)$idArr;
        $ok = $this->checkProgress($type, $status, $idArr, $enum);//判断操作是否合法
        if ($ok['type'] !== 0){
	        if ($type == $progress['已接收'] || $type == $progress['已领取']){
		        return $this->sendViewError($ok['msg']);
	        }
            return $this->sendErrorResponse(400, $ok['msg']);
        }
        $ids = implode(',', $idArr);
        $params = [
            'columns' => 'iId, iStatus, sHandleProgress',
            'conditions' => "iId in ($ids) AND bDelete = 0",
        ];
        try{
            $user = Main::getLoginUserInfo();
            $this->db->begin();
            $data = XhsysDevicerepair::find($params);
            if ($data){
                foreach ($data as $value){
                    $fina = XhsysDevicerepair::findFirst(['columns' => '*', 'conditions' => "iId = :iId: AND bDelete = 0", 'bind' => ['iId' => $value->iId]]);
                    if ($needCreater && ($type == $progress['已接收'] || $type == $progress['已领取'])){
                        if ($fina->iCreateUserId != $user['userId'] && (!User::isAdmin())){
                            return $this->sendViewError('无权限操作或存在你没有权限操作的设备，请重新选择');
                        }
                    }
                    $beforeStatus = $fina->iStatus;
                    if ($fina->iChargeType == 1 && $status == 13){//先维修后收费，确认收费时状态不变
	                    $fina->iChargeType = 2;
                    } else {
	                    $fina->iStatus = $type;
                    }
                    switch ($type){//需要记录填写内容的类型
                        case  $progress['无法维修待寄回'] :
                            $fina->sUnRepairReason = $unrepairresion;
                            $fina->sCheckContent = $chectContent;
                            $fina->sCheckReport = $checkReport;
                            break;
                        case  $progress['收费沟通中'] :
                            if (empty($project)){
                                return $this->sendErrorResponse(400, '收费项目为空');
                            }
                            $fina->sRepairProjectName = implode(',', $project);
                            $fina->iMoney = $money;
                            $fina->sCheckContent = $chectContent;
                            $fina->sCheckReport = $checkReport;
                            $fina->sExpressCharge = 14;//收费沟通时默认将运费记为14元
                            break;
                        case $progress['收费确认中'] :
                            $fina->sDisagreeReason = $backresion;
                            $fina->sDocument = $document;
                            $fina->sExpressCharge = $expressCharge;
                            $fina->tCommDate = $commDate;
	                        $fina->tLatestCommDate = $commDate;
                            $fina->sCommContent = $this->handleCommContent($fina->iId, $commDate, $backresion, $fina->sCommContent, 1);
                            $fina->iCommTimes ++;
                            break;
                        case  $progress['不同意收费待寄回'] :
                            $fina->sDisagreeReason = $backresion;
                            $fina->tCommDate = $commDate;
	                        $fina->tLatestCommDate = $commDate;
                            $fina->sCommContent = $this->handleCommContent($fina->iId, $commDate, $backresion, $fina->sCommContent, 2);
	                        $fina->iCommTimes ++;
                            break;
                        case  $progress['待维修'] :
                            //收费确认的操作
                            if ($backresion){
                                $fina->sDisagreeReason = $backresion;
                            }
                            if ($commDate){
                                $fina->tCommDate = $commDate;
	                            $fina->tLatestCommDate = $commDate;
                            }
                            if ($document){
                                $fina->sDocument = $document;
                            }
                            //检修免费的操作
                            if ($chectContent){
	                            $fina->sRepairProjectName = implode(',', $project);
                                $fina->sCheckContent = $chectContent;
	                            $fina->sCheckReport = $checkReport;
                            }
                            //沟通结果先维修后收费
                            if ($status == 18){
	                            $fina->sDisagreeReason = $backresion;
	                            $fina->sExpressCharge = $expressCharge;
	                            $fina->tCommDate = $commDate;
	                            $fina->tLatestCommDate = $commDate;
	                            $fina->sCommContent = $this->handleCommContent($fina->iId, $commDate, $backresion, $fina->sCommContent, 1);
	                            $fina->iCommTimes ++;
                            }
                            break;
                        case  $progress['维修完成'] :
                            if ($newMessage || $newDeviceNumber || $newImei){
                                $fina->iRenewal = 1;
                            }
                            $fina->sRepairContent = $repairContent;
                            $fina->sNewMessage = $newMessage ? $newMessage : '';
                            $fina->sNewDeviceNumber = $newDeviceNumber ? $newDeviceNumber : '';
                            $fina->sNewImei = $newImei ? $newImei : '';
                            break;
                        case  $progress['寄回中'] :
                            $fina->sExpBackCompany = $backExpCompany;
                            $fina->sExpressReceive = $express;
                            $fina->sExpBackDate = $backDate;
                            break;
                        case $progress['送修中'] :
                            $fina->sExpSendCompany = $sendCompany;
                            $fina->sExpressSend = $sendExpress;
                            $fina->sRepairDate = $sRepairDate;
                            break;
                        case $progress['正常开机'] :
                            if ($fina->sNewDeviceNumber) {//有新设备号
                                $this->updateDeviceInfo($fina->iUserId, $fina->iPurposeType, $fina->sDeviceNumber, $fina->sNewDeviceNumber, $fina->sModel, $fina->sNewImei, $fina->iSchoolId);
                            }
                            break;
                        default : break;
                    }
                    $fina->sHandleProgress .= ','.$type;//记录所有过程
                    switch ($status){//需要记录状态的类型
                        case  4 : $fina->iCheckResult = 3;break;
                        case  5 : $fina->iCheckResult = 2;break;
                        case  6 : $fina->iCheckResult = 1;break;
                        case  7 : $fina->iAgreeCharge = 1;$fina->bProjectChange = 0;break;
                        case  8 : $fina->iAgreeCharge = 2;break;
                        case  13: $fina->iConfirmCharge = 1;$fina->bProjectChange = 0;break;
	                    case  18: $fina->iChargeType = 1;$fina->iAgreeCharge = 2;break;
                        default : break;
                    }

                    if (in_array($status, $this->checkDelayStatus)) {//将延时状态置为空
                        $fina->iDelayStatus = 0;
                    }
                    if (!$fina->save()){
                        $this->db->rollback();
                        if ($type == $progress['已接收'] || $type == $progress['已领取']){
                            return $this->sendViewError('操作失败');
                        }
                        return $this->sendErrorResponse(500, '操作失败');
                    };

                    //记录是否延时检测
                    $delayStatus = $this->addRepairDelayData($fina->iId, $status);
                    if (!$delayStatus) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '记录延时数据失败');
                    }

                    //操作记录
                    $handle = new XhsysDevicerepairhandle();
                    $handle->iUserId = $fina->iUserId;
                    $handle->sUserName = $fina->sUserName;
                    $handle->iOperateId = $user['userId'] ? $user['userId'] : '';
                    $handle->iOperateName = $user['logonName'] ? $user['logonName'] : '';
                    $handle->iDeviceRepairId = $fina->iId;
                    $handle->iBeforeStatus = $beforeStatus;
                    $handle->iStatus = $fina->iStatus;
                    $handle->iType = $status;//点击按钮类型
                    $handle->iProgress = $fina->sHandleProgress;
                    $handle->sModel = $fina->sModel;
                    $handle->sImei = $fina->sImei;
                    $handle->sBrand = $fina->sBrand;
                    switch ($type){//记录填写的内容
                        case  $progress['无法维修待寄回'] :
                            $handle->sMessage = '检测内容：'. $fina->sCheckContent.'；无法维修原因：'. $fina->sUnRepairReason;
                            break;
                        case  $progress['收费沟通中'] :
                            $handle->sMessage = '检测内容：'. $fina->sCheckContent.'；收费项目：'. $fina->sRepairProjectName.'；维修金额：'.$fina->iMoney;
                            break;
                        case  $progress['不同意收费待寄回'] : $handle->sMessage = '沟通内容/原因：'. $fina->sDisagreeReason;break;
                        case  $progress['收费确认中'] :
                            $handle->sMessage = '收费沟通内容：'. $fina->sDisagreeReason;
                            $handle->sMessage .= '；运费：'. $fina->sExpressCharge;
                            break;
                        case  $progress['待维修'] :
                            if ($chectContent){//检修免费，若确认收费不记录
                                $handle->sMessage = '检测内容：'. $fina->sCheckContent.'；';
                            }
                            if ($status == 18){
	                            $handle->sMessage = '(先维修再收费)检测内容：'. $fina->sCheckContent.'；';
                            }
                            break;
                        case  $progress['维修完成'] :
                            $handle->sMessage = '维修内容：' . $fina->sRepairContent;
                            if ($fina->iRenewal == 1){
                                $handle->sMessage .= '；维修后有信息变化：';
                                if ($fina->sNewDeviceNumber){
                                    $handle->sMessage .= '（新设备号）' . $fina->sNewDeviceNumber . '；';
                                    $handle->sMessage .= '（新Imei号）' . $fina->sNewImei . '；';
                                }
                                if ($fina->sNewMessage){
                                    $handle->sMessage .= '（其他变化信息）' . $fina->sNewMessage;
                                }
                            }

                            break;
                        case  $progress['寄回中'] : $handle->sMessage = '寄回快递单号：('.$fina->sExpBackCompany.')'.$fina->sExpressReceive . '；寄回时间：' . $backDate;break;
                        case  $progress['返回重修'] :
                            if ($backdest == 1){
                                $handle->sMessage = '目的地：公司，故障描述：' . $backremark;
                            }else{
                                $handle->sMessage = '目的地：检修站，快递信息：('.$backexpressCompany.')'.$backexpress.'；故障描述：' . $backremark;
                            }
                            break;
                        case $progress['送修中'] :
                            $handle->sMessage = '送修时间：' . $sRepairDate . '；快递信息：(' . $sendCompany . ')' . $sendExpress;
                            break;
                        default : break;
                    }
                    if (!$handle->save()){
                        $this->db->rollback();
                        if ($type == $progress['已接收'] || $type == $progress['已领取']){
                            return $this->sendViewError('[操作失败]保存记录失败');
                        }
                        return $this->sendErrorResponse(500, '[操作失败]保存记录失败');
                    }

                    //如果是返回重修，新增一条记录，原记录流程结束
                    if ($type == $progress['返回重修']){
                        $newData = new XhsysDevicerepair();
                        $newData->iUserId = $fina->iUserId;
                        $newData->iSchoolId = $fina->iSchoolId;
                        $newData->sUserName = $fina->sUserName;
                        $newData->sLogonName = $fina->sLogonName;
                        $newData->sModel = $fina->sModel;
                        $newData->sImei = $fina->sImei;
                        $newData->sBrand = $fina->sBrand;
                        $newData->sDeviceNumber = $fina->sDeviceNumber;
                        if ($backdest == 2){
                            if (!$backexpress || !$backexpressCompany){
                                $this->db->rollback();
                                return $this->sendErrorResponse(400, '请输入快递公司或快递号');
                            }
                            $newData->iStatus = $progress['送修中'];
                            $newData->sHandleProgress = $progress['未开始'].','.$progress['已接收'].','.$progress['送修中'];
                            $newData->sRepairDate = $sRepairDate;
                            $newData->sExpSendCompany = $backexpressCompany;
                            $newData->sExpressSend = $backexpress;
                        }
                        $newData->iCreateType = $fina->iCreateType;
                        $newData->iPurposeType = $fina->iPurposeType;
                        $newData->sProduct = $fina->sProduct;
                        $newData->iDestination = $backdest;
                        $newData->sRemark = $backremark;
                        if (!$newData->save()){
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '保存出错');
                        }
                    }
                    //若用途是库存机且是公司送修时设备出库
                    if ($fina->iDestination == 1 && $fina->iPurposeType == 6 && ($fina->sProduct) && $type == 2){
                        try{
//                            Ims::resOut(['iProdId' => $fina->sProduct, 'iOutNum' => 1], [], '设备维修出库', User::getId());
                            Ims::prodOut(['iProdId' => $fina->sProduct, 'iOutNum' => 1, 'iOutType' => 4], [], '设备维修出库', User::getId());
                        } catch (\Exception $e){
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '出库错误：' . $e->getMessage());
                        }
                    }
                    //若用途是库存机维修结果时设备入库
                    if ($fina->iPurposeType == 6 && ($fina->sProduct) && in_array($type, [10, 11])){
                        try{
//                            Ims::resIn(['iProdId' => $fina->sProduct, 'iProdNum' => 1], [], '设备维修返回入库', User::getId());
                            Ims::prodIn(['iProdId' => $fina->sProduct, 'iInNum' => 1, 'iInType' => 3 , 'iInTypeId' =>  $fina->iId], [], '设备维修返回入库', User::getId());
                        } catch (\Exception $e){
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '出库错误：' . $e->getMessage());
                        }
                    }
                }
                $this->db->commit();
                if ($type == $progress['已接收'] || $type == $progress['已领取']){
                    return $this->sendViewSuccess('成功');
                }
                return $this->sendSuccessResponse('成功');
            }else{
                $this->db->rollback();
                if ($type == $progress['已接收'] || $type == $progress['已领取']){
                    return $this->sendViewError('无数据');
                }
                return $this->sendErrorResponse(500, '无数据');
            }
        }catch (\Exception $e){
            $this->db->rollback();
            if ($type == $progress['已接收'] || $type == $progress['已领取']){
                return $this->sendViewError($e->getMessage());
            }
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 判断修改状态是否符合要求，不能重新操作，不能越级操作
     *
     * @return array
     *
     * create by qgz 20180511
     * modify by qgz 20180622 管理员可操作所有类型
     */
    public function checkProgress($type, $status, $idArr, $enum){
        $isAdmin = User::isAdmin();
        $ids = implode(',', $idArr);
        $params = [
            'columns' => 'iId, iStatus, sHandleProgress, sBrand, iCreateUserId, iPurposeType, iChargeType',
            'conditions' => "iId in ($ids) AND bDelete = 0",
        ];
        $progress = array_flip($enum);
        //逐步操作次序
        $nextProgress = [
            $progress['未开始'] => [$progress['已接收']],
            $progress['已接收'] => [$progress['送修中']],
            $progress['送修中'] => [$progress['在检测']],
            $progress['在检测'] => [$progress['无法维修待寄回'], $progress['待维修'], $progress['收费沟通中']],
            $progress['无法维修待寄回'] => [$progress['寄回中']],
            $progress['收费沟通中'] => [$progress['不同意收费待寄回'], $progress['收费确认中']],
            $progress['收费确认中'] => [$progress['待维修']],
            $progress['不同意收费待寄回'] => [$progress['寄回中']],
            $progress['待维修'] => [$progress['维修中']],
            $progress['维修中'] => [$progress['维修完成']],
            $progress['维修完成'] => [$progress['寄回中']],
//            $progress['寄回中'] => [$progress['正常开机'], $progress['返回重修'], $progress['未维修']],
            $progress['寄回中'] => [$progress['已领取']],
//            $progress['正常开机'] => [['未领取']],
//            $progress['未维修'] => [['未领取']],
            $progress['已领取'] => [$progress['正常开机'], $progress['返回重修'], $progress['未维修']],
        ];
        //先维修后收费
        if ($status == 18){
	        $nextProgress[$progress['收费沟通中']] = [$progress['不同意收费待寄回'], $progress['收费确认中'], $progress['待维修']];
	        $nextProgress[$progress['收费确认中']] = [];
	        $nextProgress[$progress['在检测']] = [];
        }
        $data = XhsysDevicerepair::find($params)->toArray();
        if (empty($data)){
            return ['type' => 1, 'msg' => '找不到数据'];
        }

        $findBrand = [];
        foreach ($data as $value){
            if (!in_array($value['sBrand'], $findBrand)){
                $findBrand[] = $value['sBrand'];
            }
        }
        unset($value);
        //需要特殊判断的操作，如送修多选品牌唯一
        if ($type == $progress['送修中'] && count($findBrand) > 1){
            return ['type' => 5, 'msg' => '请选择同一品牌打包送修'];
        }

        $userId = User::getId();
        foreach ($data as $value){
            //用途是库存的跳过某些步骤
            if ($value['iPurposeType'] == 6){
                $nextProgress[$progress['未开始']] = [$progress['送修中']];
                $nextProgress[$progress['寄回中']] = [$progress['正常开机'], $progress['返回重修'], $progress['未维修']];
                $nextProgress[$progress['收费沟通中']] = [$progress['待维修']];
            }
	        if ($value['iChargeType'] == 1 && $status == 13){//先维修后收费，只在维修后和领取前可收费确认
		        if (!in_array($value['iStatus'], [$progress['待维修'], $progress['维修中'], $progress['维修完成'], $progress['寄回中']])  && !$isAdmin){
			        return ['type' => 3, 'msg' => '越级或非法操作，请重新选择'];
		        }
	        } else {
		        //不是下一步要做的操作,管理员跳过
		        if (!in_array($type, $nextProgress[$value['iStatus']]) && !$isAdmin){
			        return ['type' => 3, 'msg' => '越级或非法操作，请重新选择'];
		        }
	        }
            //特殊操作
            if ((($status == 6 && $value['iStatus'] == $progress['收费确认中']) || ($status == 13 && $value['iStatus'] == $progress['在检测'])) && !$isAdmin){
                return ['type' => 4, 'msg' => '操作有误，请重新选择'];
            }

            if ((in_array($type, [10, 11, 12]) && $userId != $value['iCreateUserId']) && !$isAdmin){//维修结果只有申请人可操作
                return ['type' => 5, 'msg' => '存在你没权限查看维修结果的选项，请重新选择操作'];
            }
            if (($value['iChargeType'] == 1 && $type == 15) && !$isAdmin){
	            return ['type' => 6, 'msg' => '有收费项还未确认，请确认收费'];
            }
            //重置状态顺序
	        if ($value['iPurposeType'] == 6){
	            $nextProgress[$progress['未开始']] = [$progress['已接收']];
	            $nextProgress[$progress['寄回中']] = [$progress['已领取']];
		        if ($status == 18){
			        $nextProgress[$progress['收费沟通中']] = [$progress['不同意收费待寄回'], $progress['收费确认中'], $progress['待维修']];
		        } else {
			        $nextProgress[$progress['收费沟通中']] = [$progress['不同意收费待寄回'], $progress['收费确认中']];
		        }
            }
        }
        return ['type' => 0, 'msg' => ''];
    }

    /**
     * 延时延时记录
     *
     * @param $id
     * @param $status
     *
     * @return bool
     *
     * create by qgz 20180913
     */
    public function addRepairDelayData($id, $status)
    {
        if (!in_array($status, $this->checkDelayStatus)) {//需要记录延时的进行记录
            return true;
        }
        $iProgressStatus = '';
        if (in_array($status, [2, 4, 5, 6])) {
            $iProgressStatus = 1;
        } elseif (in_array($status, [7, 8, 18])) {
            $iProgressStatus = 2;
        } elseif (in_array($status, [13])) {
            $iProgressStatus = 3;
        } elseif (in_array($status, [9])) {
            $iProgressStatus = 4;
        }
        $delayPro = XhsysDevicerepairDelay::findFirst([
            'conditions' => 'bDelete = 0 and iRepairApplyId = :iRepairApplyId: and iProgressStatus = :iProgressStatus:',
            'bind' => ['iRepairApplyId' => $id, 'iProgressStatus' => $iProgressStatus]
        ]);
        $delayPro = $delayPro ? $delayPro : new XhsysDevicerepairDelay();
        switch ($iProgressStatus) {
            case 1 ://检测
                if (in_array($status, [2])) {//开始
                    $delayPro->iRepairApplyId = $id;
                    $delayPro->iProgressStatus = 1;
                    $delayPro->iFinishStatus = 0;
                    $delayPro->iDelayStatus = 0;
                    $delayPro->tStartDate = date('Y-m-d');
                    $delayPro->tEndDate = $this->handleEndDate(date('Y-m-d'), 2);
                } elseif (in_array($status, [4, 5, 6])) {//结束
                    $delayPro->tRealEnd = date('Y-m-d');
                    $delayPro->iFinishStatus = 1;
                    $delayPro->iDelayStatus = $delayPro->tEndDate < date('Y-m-d') ? 1 : 0;
                    if ($status == 5) {//收费上传报告，进入收费沟通时效
                        $addDelayData = $this->addDelayData($id, 2, 2);
                        if (!$addDelayData) {
                            return false;
                        }
                    }
                    if ($status == 6) {//免费时跳过两步
                        $addDelayData = $this->addDelayData($id, 4, 7);
                        if (!$addDelayData) {
                            return false;
                        }
                    }
                }
                break;
            case 2 : //收费沟通
                if ($delayPro->iRepairApplyId) { //有记录才修改状态
                    $delayPro->tRealEnd = date('Y-m-d');
                    $delayPro->iFinishStatus = 1;
                    $delayPro->iDelayStatus = $delayPro->tEndDate < date('Y-m-d') ? 1 : 0;
                }
                if (in_array($status, [8])) {//只有先收费后维修有收费确认时效
                    $addDelayData = $this->addDelayData($id, 3, 2);
                    if (!$addDelayData) {
                        return false;
                    }
                }
                break;
            case 3 : //收费确认
                if ($delayPro->iRepairApplyId) { //有记录才修改状态
                    $delayPro->tRealEnd = date('Y-m-d');
                    $delayPro->iFinishStatus = 1;
                    $delayPro->iDelayStatus = $delayPro->tEndDate < date('Y-m-d') ? 1 : 0;
                    $addDelayData = $this->addDelayData($id, 4, 7);//维修时效
                    if (!$addDelayData) {
                        return false;
                    }
                }
                break;
            case 4 : //维修
                if ($delayPro->iRepairApplyId) { //有记录才修改状态
                    $delayPro->tRealEnd = date('Y-m-d');
                    $delayPro->iFinishStatus = 1;
                    $delayPro->iDelayStatus = $delayPro->tEndDate < date('Y-m-d') ? 1 : 0;
                }
                break;
        }
        if (!$delayPro->save()) {
            return false;
        }
        return true;
    }

    /**
     * 添加延时记录数据
     *
     * @param $id
     * @param $delayStatus
     * @param $dayNum
     *
     * @return bool
     *
     * create by qgz 20180913
     */
    public function addDelayData($id, $delayStatus, $dayNum)
    {
        $project = XhsysDevicerepairDelay::findFirst([
            'conditions' => 'bDelete = 0 and iRepairApplyId = :iRepairApplyId: and iProgressStatus = :iProgressStatus:',
            'bind' => ['iRepairApplyId' => $id, 'iProgressStatus' => $delayStatus]
        ]);
        $project = $project ? $project : new XhsysDevicerepairDelay();
        $project->iRepairApplyId = $id;
        $project->iProgressStatus = $delayStatus;
        $project->iFinishStatus = 0;
        $project->iDelayStatus = 0;
        $project->tStartDate = date('Y-m-d');
        $project->tEndDate = $this->handleEndDate(date('Y-m-d'), $dayNum);
        if (!$project->save()) {
            return false;
        }
        return true;
    }

    /**
     * 根据$date日期获取$day个工作日后的日期
     *
     * @param $date
     * @param $day
     *
     * @return mixed
     *
     * create by qgz 20180913
     */
    public function handleEndDate($date, $day)
    {
        $dateArr = [];
        for ($i = 0; $i <= 10; $i++) {//最大是7天后的，设置$i为10
            $dateArr[] = date("Y-m-d",strtotime("+".$i." day",strtotime($date)));
        }
        $workDay = [];
        foreach ($dateArr as $item){
            if (!in_array(date('w', strtotime($item)), [0, 6])) {
                $workDay[] = $item;
            }
        }
        return $workDay[$day-1];
    }

    /**
     * 设备维修后新设备号--更新到绑定表和授权表
     *
     * @param $userId
     * @param $purposeType
     * @param $oldDevice
     * @param $newDevice
     * @param $model
     * @param $IMei
     * @param $schoolId
     *
     * @return bool
     * @throws \Exception
     *
     * create by qgz 20190222
     */
    public function updateDeviceInfo($userId, $purposeType, $oldDevice, $newDevice, $model, $IMei, $schoolId)
    {
        if (!$userId || !$purposeType || !$oldDevice || !$newDevice || $oldDevice == $newDevice) {
            return true;
        }
        if ($purposeType == 1) {//学生机
            //更新绑定表
            $findBound = XhsysAccountdevicelocked::find([
                'conditions' => 'bDelete = 0 and (iUserId = :iUserId: or sDeviceNumber = :sDeviceNumber: )',
                'bind' => ['iUserId' => $userId, 'sDeviceNumber' => $oldDevice]
            ]);
            if (!$findBound) {
                return true;
            }
            foreach ($findBound as $item) {
                $item->bDelete = 1;//置为历史
                $item->sNewDevice = $newDevice;
                $item->iNewUserId = $userId;
                if (!$item->save()) {
                    $this->createCommitLog('设置绑定表为历史失败','绑定id：' . $item->iADLId . '账号：' . $item->sLogonName . '设备：' . $item->sDeviceNumber);
                    return false;
                }
                $this->createCommitLog('设置绑定表为历史成功','绑定id：' . $item->iADLId . '账号：' . $item->sLogonName . '设备：' . $item->sDeviceNumber);
            }
            $newPro = new XhsysAccountdevicelocked();
            $newPro->iUserId = $userId;
            $newPro->sLogonName = User::getLogonName($userId);
            $newPro->sDeviceNumber = $newDevice;
            $newPro->sModel = $model;
            $newPro->sImei = $IMei;
            if (!$newPro->save()) {
                $this->createCommitLog('新增绑定表失败','用户id：' . $userId . '设备：' . $newDevice);
                return false;
            }
            $this->createCommitLog('新增绑定表成功','用户id：' . $userId . '设备：' . $newDevice);
            return true;
        } elseif ($purposeType != 6) {//除库存机外的其他类型
            //更新授权表
            //将授权表原数据置为历史，新建一条授权记录
            $tabletData = XhsysUsertablet::findFirst([
                'conditions' => 'bDelete = 0 and bHistory = 0 and sDevNumber = :sDevNumber: ',
                'bind' => ['sDevNumber' => $oldDevice]
            ]);
            $newPurposeArr = [2 => 0, 3 => 1, 4 => 2, 5 => 3];//用途code转换下
            if ($tabletData) {
                $newPro = new XhsysUsertablet();
                $receiverId = User::getId();
                $receiverInfo = XhsysUser::getUserInfoById($receiverId);//申领人是当前操作的人
                $newPro->sReceiverName = $receiverInfo['sUserName'];
                $newPro->sReceiverAccount = $receiverInfo['sLogonName'];
                $newPro->sReceiverPhone = $receiverInfo['sSelfPhone'];
                $newPro->iReceivePurpose = $newPurposeArr[$purposeType];
                $newPro->tReceiveTime = date('Y-m-d H:i:s');
                $newPro->sDevNumber = $newDevice;
                if ($userId) {//计新的具体数据，前身具体数据不计表，仅计老的id
                    $nowReceiverInfo = XhsysUser::getUserInfoById($userId);//当前申领人
                    $newPro->iNowReceiverId = $userId;
                    $newPro->sNowReceiverName = $nowReceiverInfo['sUserName'];
                    $newPro->sNowReceiverAccount = $nowReceiverInfo['sLogonName'];
                    $newPro->tNowReceiveTime = date('Y-m-d H:i:s');
                }
                $newPro->iSource = 2;
                $newPro->sDevType = $model;
                $newPro->iSchoolId = $schoolId ?: '';
                $newPro->iBeforeUTId = $tabletData->iUTId;//前身id
                if (!$newPro->save()) {
                    $this->createCommitLog('新增授权表失败','用户id：' . $userId . '设备：' . $newDevice);
                    return false;
                }
                $tabletData->iNewUTId = $newPro->iUTId;//后世id
                $tabletData->sNewReceiver = User::getId();
                $tabletData->iNewPurpose = $newPurposeArr[$purposeType];
                $tabletData->sNewNowReceiver = $userId ?: '';
                $tabletData->bHistory = 1;
                if (!$tabletData->save()) {
                    $this->createCommitLog('更新授权表失败','用户id：' . $userId . '保存授权表出错，id:' . $tabletData->iUTId);
                    return false;
                }
            }
            $this->createCommitLog('更新绑定表成功','用户id：' . $userId . '设备：' . $newDevice);
            return true;
        }
        return true;
    }

    /**
     * 修改设备维修页
     *
     * @return mixed
     *
     * create by qgz 20180604
     */
    public function modifyInfoAction(){
        Assets::easyUI('js/device/modifyInfo.js');
        $this->view->pick('device/modifyInfoForm');
        $id = $this->request->getQuery('id');
        if (!UserPower::checkUserPower('Device_Repair_Edit')) {
            return $this->sendViewError('对不起，您没有操作权限');
        }
        $deviceData = XhsysDevicerepair::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 AND iId = :iTd:', 'bind' => ['iTd' => $id]]);
        if (!$deviceData){
            return $this->sendViewError('没有维修数据');
        }
        $otherInfo = [];
        if ($deviceData->iCreateType == 1){
            $userInfoArr = XhsysUser::findFirst([
                'columns' => 'sUserName, sMotherPhone, sFatherPhone, sOtherPhone',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind' => ['iUserId' => $deviceData->iUserId]
            ]);
            if (!$userInfoArr){
                $this->sendViewError('暂无该学生数据');
            }
            $userStud = XhsysUserstud::findFirst([
                'columns' => 'sMotherName, sFatherName, sOtherName',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind' => ['iUserId' => $deviceData->iUserId]
            ]);

            $otherInfo = [
                'fatherInfo' => ['name' => $userStud ? $userStud->sFatherName : '', 'phone' => $userInfoArr->sFatherPhone],
                'motherInfo' => ['name' => $userStud ? $userStud->sMotherName : '', 'phone' => $userInfoArr->sMotherPhone],
                'guardInfo' => ['name' => $userStud ? $userStud->sOtherName : '', 'phone' => $userInfoArr->sOtherPhone],
            ];
        }

        $deviceData = $deviceData->toArray();
        $deviceData['iDestination'] = $this->registerEnum['destination'][$deviceData['iDestination']];
        $deviceData['iStatus'] = $this->registerEnum['progress'][$deviceData['iStatus']];
        $deviceData = [$deviceData];
        if ($deviceData[0]['iSchoolId']){
            Main::runSchoolNameByIdStr($deviceData, ['iSchoolId' => 'sSchoolName']);
        }else{
            $deviceData[0]['sSchoolName'] = '';
        }
        $this->view->setVars([
            'id' => $id,
            'type' => $deviceData[0]['iCreateType'],
            'repairInfo' => $deviceData[0],
            'otherInfo' => $otherInfo
        ]);
    }

    /**
     * 保存设备维修修改信息
     *
     * @return mixed
     *
     * create by qgz 20180604
     */
    public function saveRepairInfoAction(){
        $data = $this->request->getPost();
        $deviceData = XhsysDevicerepair::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 AND iId = :iTd:', 'bind' => ['iTd' => $data['id']]]);
        if (!$deviceData){
            return $this->sendErrorResponse(500, '没有维修数据');
        }
        $this->db->begin();
        $deviceData->sRemark = $data['sRemark'];
        $deviceData->sModel = $data['model'];
        $deviceData->sDeviceNumber = $data['deviceNumber'];
        $deviceData->sBrand = $data['sBrand'];
        $deviceData->sImei = $data['sImei'];
        if (!$deviceData->save()){
            $this->db->rollback();
            return $this->sendErrorResponse(500,'保存维修数据出错');
        }

        if ($deviceData->iUserId && $deviceData->iCreateType == 1){
            //存父母电话
            $userInfo = XhsysUser::findFirst([
                'columns' => '*',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind' => ['iUserId' => $deviceData->iUserId]
            ]);
            if (!$userInfo){
                return $this->sendErrorResponse(500, '暂无该学生数据');
            }
            $userInfo->sMotherPhone = $data['motherPhone'];
            $userInfo->sFatherPhone = $data['fatherPhone'];
            $userInfo->sOtherPhone = $data['guardPhone'];
            if (!$userInfo->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '保存电话信息出错');
            }

            //存父母姓名
            $userStud = XhsysUserstud::findFirst([
                'columns' => '*',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind' => ['iUserId' => $deviceData->iUserId]
            ]);
            if (!$userStud){
                $userStud = new XhsysUserstud();
                $userStud->iUserId = $deviceData->iUserId;
            }
            //存父母姓名
            $userStud->sMotherName = $data['motherName'];
            $userStud->sFatherName = $data['fatherName'];
            $userStud->sOtherName = $data['guardName'];
            if (!$userStud->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '保存家长姓名出错');
            }
        }
        $this->db->commit();
        return $this->sendSuccessResponse('修改成功');
    }
    /**
     * 设置金额页
     *
     *
     * create by qgz 20180515
     * modify by qgz 20180524 项目多选计算总值
     */
    public function setChargeAction(){
        Assets::UMEditor();
        Assets::select2();
        Assets::importMainJs('assets/jquery/ajaxfileupload.js');
        Assets::easyUI('js/device/setCharge.js');
        $this->view->pick('device/setChargeForm');

        $id = $this->request->getQuery('ids');
        $type = $this->request->getQuery('type');
        $status = $this->request->getQuery('status');
        $model = $this->request->getQuery('model');
	    $free = $this->request->getQuery('free');
        $params = [
            'columns' => '*',
            'conditions' => 'bDelete = 0 AND sTypeName = :sTypeName:',
            'bind' => ['sTypeName' => $model]
        ];
        $return = [];
        $data = XhsysDevicerepairProject::find($params)->toArray();
        if (!empty($data)){
            foreach ($data as $value){
                $return[$value['sProjectName']] = $value['sProjectName'];
            }
        }

        $this->view->setVars([
            'id' => $id,
            'type' => $type,
            'status' => $status,
            'model' => $model,
            'free' => $free,
            'project' => json_encode(['project' => $return])
        ]);
    }

	/**
	 * 修改金额页
	 *
	 *
	 * create by qgz 20180703
	 */
	public function modifyChargeAction(){
		Assets::select2();
		Assets::easyUI('js/device/modifyCharge.js');
		$this->view->pick('device/modifyChargeForm');
		$id = $this->request->getQuery('id');

		$params = [
			'columns' => '*',
			'conditions' => 'bDelete = 0 AND iId = :iId:',
			'bind' => ['iId' => $id]
		];
		$data = XhsysDevicerepair::findFirst($params);
		if (!$data){
			return $this->sendViewError('找不到数据');
		}
		$data = $data->toArray();
		$project = $allProject = [];
		if ($data['sRepairProjectName']){
			$project = explode(',', $data['sRepairProjectName']);
		}
		//获取该类型所有维修项目数据
		$params = [
			'columns' => '*',
			'conditions' => 'bDelete = 0 AND sTypeName = :sTypeName:',
			'bind' => ['sTypeName' => $data['sModel']]
		];
		$projectData = XhsysDevicerepairProject::find($params)->toArray();
		if (!empty($projectData)){
			foreach ($projectData as $value){
				$allProject[] = ['id' => $value['sProjectName'], 'text' => $value['sProjectName']];
			}
		}
		$this->view->setVars([
			'allProject' => json_encode(['project' => $allProject]),
			'project' => json_encode($project),
			'money' => $data['iMoney'],
			'model' => $data['sModel']
		]);
	}

    /**
     * 获取项目名称数据
     *
     * @return string
     *
     * create by qgz 20180516
     */
    public function getProjectDataAction(){
        $model = $this->request->getPost('model');
        $params = [
            'columns' => '*',
            'conditions' => 'bDelete = 0 AND sTypeName = :sTypeName:',
            'bind' => ['sTypeName' => $model]
        ];
        $data = XhsysDevicerepairProject::find($params)->toArray();
        if (empty($data)){
            return json_encode([]);
        }
        foreach ($data as $value){
            $return[$value['sProjectName']] = $value['sProjectName'];
        }
//        return json_encode($return);
        return $return;
    }

    /**
     * 根据项目名获取金额
     *
     * @return string
     *
     * create by qgz 20180516
     * modify by qgz 20180524 项目多选计算总值
     */
    public function getChargeDataAction(){
        $project = $this->request->getPost('project');
        $model = $this->request->getPost('model');
        if (empty($project)){
            return json_encode([]);
        }
        $project = "('".implode("','", $project)."')";
        $params = [
            'columns' => '*',
            'conditions' => 'bDelete = 0 AND sProjectName in ' . $project . ' AND sTypeName = :sTypeName:',
            'bind' => ['sTypeName' => $model]
        ];
        $data = XhsysDevicerepairProject::find($params);
        if (empty($data)){
            return json_encode([]);
        }
        $data = $data->toArray();
        $return = 0;
        foreach ($data as $value){

            $return = $return + $value['sProjectPay'];
        }
        return $return == 0 ? json_encode([]) : json_encode($return);
    }

	/**
	 * 修改收费项目
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180705
	 */
    public function modifyChargeDataAction(){
    	$id = $this->request->getPost('id');
	    $project = $this->request->getPost('project');
	    $money = $this->request->getPost('money');
	    if (!$id || empty($project) || !$money){
		    return $this->sendErrorResponse(400, '请选择后操作');
	    }
	    $data = XhsysDevicerepair::findFirst(['columns' => '*', 'conditions' => ' bDelete = 0 AND iId = :iId:', 'bind' => ['iId' => $id]]);
	    if (!$data){
		    return $this->sendErrorResponse(500, '暂无数据');
	    }
	    $data->sRepairProjectName = implode(',', $project);
	    $data->iMoney = $money;
	    $data->bProjectChange = 1;//维修项目发生改变
	    if (!$data->save()){
		    return $this->sendErrorResponse(500, '保存失败');
	    }
	    return $this->sendSuccessResponse('成功');
    }

	/**
	 * 获取状态枚举
	 *
	 * @return string
	 *
	 * create by qgz 20180705
	 */
    public function getStatusArrAction(){
    	return json_encode($this->registerEnum['progress']);
    }

	/**
	 * 修改状态
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180705
	 * modify by qgz 20180711 直接修改状态记录过程
     * modify by qgz 20181109 支持批量修改
	 */
    public function modifyStatusAction(){
	    $id = $this->request->getPost('id');
	    $status = $this->request->getPost('statusCode');
	    $buttonType = $this->request->getPost('status');
	    if (!$id){
		    return $this->sendErrorResponse(400, '请选择后操作');
	    }
	    $this->db->begin();
	    $allData = XhsysDevicerepair::find([
	        'conditions' => ' bDelete = 0 AND iId in ({idArr:array}) ',
            'bind' => ['idArr' => $id]
        ]);
	    if (!$allData) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '暂无数据');
        }
        foreach ($allData as $data) {
            $beforeStatus = $data->iStatus;
            $data->iStatus = $status;
            $data->sHandleProgress .= ',' . $status;
            if (!$data->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '保存失败');
            }
            //操作记录
            $user = Main::getLoginUserInfo();
            $handle = new XhsysDevicerepairhandle();
            $handle->iUserId = $data->iUserId;
            $handle->sUserName = $data->sUserName;
            $handle->iOperateId = $user['userId'] ? $user['userId'] : '';
            $handle->iOperateName = $user['logonName'] ? $user['logonName'] : '';
            $handle->iDeviceRepairId = $data->iId;
            $handle->iBeforeStatus = $beforeStatus;
            $handle->iStatus = $status;
            $handle->iType = $buttonType;//点击按钮类型
            $handle->iProgress = $data->sHandleProgress;
            $handle->sModel = $data->sModel;
            $handle->sImei = $data->sImei;
            $handle->sBrand = $data->sBrand;
            $handle->sMessage = '（直接修改状态）：'."从'".$this->registerEnum['progress'][$beforeStatus]."'修改为'".$this->registerEnum['progress'][$status]."'";
            if (!$handle->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '[操作失败]保存记录失败');
            }
        }
//	    $data = XhsysDevicerepair::findFirst(['columns' => '*', 'conditions' => ' bDelete = 0 AND iId = :iId:', 'bind' => ['iId' => $id]]);
//	    if (!$data){
//	    	$this->db->rollback();
//		    return $this->sendErrorResponse(500, '暂无数据');
//	    }

	    $this->db->commit();
	    return $this->sendSuccessResponse('修改成功');
    }


    /**
     * 设备维修操作记录页
     *
     * @return mixed
     *
     * create by qgz 20180511
     */
    public function repairHandleListAction(){
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/device/repairHandleList.js');
        $listSearchArr = $listButtonArr = [];
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHSys_RepairHandleList', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ]);
    }

    /**
     * 延时情况
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20180914
     */
    public function repairDelayListAction(){
        $id = $this->request->get('id');
        if (!$id){
            return $this->sendViewError('缺少参数');
        }
        $this->view->pick('device/repairDelay');
        $status = $this->delayStatus;
        $statusArr = array_keys($status);
        $allData = XhsysDevicerepairDelay::find([
            'conditions' => 'bDelete = 0 and iRepairApplyId = :iRepairApplyId:',
            'bind' => ['iRepairApplyId' => $id]
        ])->toArray();
        $data = [];
        foreach ($statusArr as $value) {
            $single['status'] = $status[$value];
            $single['finish'] = '无';
            $single['startDate'] = $single['endDate'] = $single['realEndDate'] = $single['delayDayNum'] = '';
            if ($allData) {
                foreach ($allData as $datum) {
                    if ($datum['iProgressStatus'] == $value) {
                        $single['finish'] = $datum['iFinishStatus'] == 1 ? '已完成' : '无';
                        $single['startDate'] = $datum['tStartDate'];
                        $single['endDate'] = $datum['tEndDate'];
                        $single['realEndDate'] = $datum['tRealEnd'];
                        if ($datum['iDelayStatus'] == 1) {
                            $endDate = $datum['iFinishStatus'] == 1 ? $datum['tRealEnd'] : date('Y-m-d');
                            $single['delayDayNum'] = $this->getDays($datum['tEndDate'], $endDate);
                        }
                    }
                }
            }
            $data[] = $single;
        }
        return $this->view->setVars([
            'data' => $data
        ]);
    }

    /**
     * 根据时间算出间隔多少个工作日
     *
     * @param $fromAt
     * @param $endAt
     *
     * @return float|int
     *
     * create by qgz 20180914
     */
    public function getDays($fromAt, $endAt)
    {
        $date1 = strtotime($fromAt);
        $date2 = strtotime($endAt);
        $delta = ($date2 - $date1) / (60 * 60 * 24);
        $weekEnds = 0;
        for ($i = 0; $i < $delta; $i++) {
            if (date('w', $date1) == 0 || date('w', $date1) == 6) {
                $weekEnds++;
            }
            $date1 += 60 * 60 * 24;
        }
        return $delta - $weekEnds;
    }

    /**
     * 记录沟通内容
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180625
     */
    public function setCommDataAction(){
        $postData = $this->request->getPost();
        if (!$postData['id']){
            return $this->sendErrorResponse(400, '请选择后操作');
        }
        if (!$postData['commDate'] || !$postData['commContent']){
            return $this->sendErrorResponse(400, '请输入完整信息');
        }
        $commData = XhsysDevicerepair::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
        if (!$commData){
            return $this->sendErrorResponse(500, '暂无数据');
        }
        $data = [
            'createrId' => User::getId(),
            'type' => 3,//1同意收费2不同意3正常沟通
            'createDate' => date('Y-m-d H:i:s', time()),
            'commContent' => $postData['commContent'],
            'commDate' => $postData['commDate']
        ];
        if (!$commData->sCommContent){//未记录
            $commMsg = [
                'iId' => $commData->iId,
                'times' => 1,
                'data' => [$data]
            ];
        } else {//已记录
            $commMsg = json_decode($commData->sCommContent, true);
            $commMsg['data'][] = $data;
            $commMsg['times']++;
        }
        $commData->sCommContent = json_encode($commMsg, JSON_UNESCAPED_UNICODE);
	    $commData->iCommTimes ++;
	    $commData->tLatestCommDate = $postData['commDate'];
        if (!$commData->save()){
            return $this->sendErrorResponse(500, '保存失败');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 处理沟通内容字段
     * @param $type 1同意收费2不同意3正常沟通
     * @return string
     *
     * create by qgz 20180626
     */
    public function handleCommContent($iId='', $date='', $content='', $commContent, $type){
        $data = [
            'createrId' => User::getId(),
            'type' => $type,
            'createDate' => date('Y-m-d H:i:s', time()),
            'commContent' => $content,
            'commDate' => $date
        ];
        if (!$commContent){//未记录
            $commMsg = [
                'iId' => $iId,
                'times' => 1,
                'data' => [$data]
            ];
        } else {//已记录
            $commMsg = json_decode($commContent, true);
            $commMsg['data'][] = $data;
            $commMsg['times']++;
        }
        return json_encode($commMsg, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取沟通记录
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20180626
     */
    public function getCommHistoryAction(){
        $id = $this->request->getQuery('id');
        $this->view->pick('device/repairComm');
        if (!$id){
            return $this->sendViewError('缺少参数');
        }
        $data = XhsysDevicerepair::findFirst([
            'columns' => 'sCommContent',
            'conditions' => ' bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $id]
        ]);
        if (!$data){
            return $this->sendViewError('暂无数据');
        }
        if ($data->sCommContent){
            $commContent = json_decode($data->sCommContent, true);
            foreach ($commContent['data'] as &$value){
                $value['type'] = $this->registerEnum['commType'][$value['type']];
            }
            $fina['total'] = $commContent['times'];
            $fina['data'] = $commContent['data'];
        } else {
            $fina['total'] = 0;
        }
        return $this->view->setVars([
            'data' => $fina
        ]);
    }

    /**
     * 获取设备检修操作历史数据
     *
     * @return mixed
     *
     * create by qgz 20180511
     */
    public function getRepairHandleDataAction(){
        $id = $this->request->getPost('id');
        $parameters = [
            'columns' => '*',
            'conditions' => ' bDelete = 0 AND iDeviceRepairId = :iDeviceRepairId:',
            'bind' => ['iDeviceRepairId' => $id]
        ];
        $enum = $this->registerEnum['progress'];
        $data = Main::runModelPage('Admin\Models\device\XhsysDevicerepairhandle', $parameters, ['iBeforeStatus' => $enum,'iStatus' => $enum]);
        Main::runUserNameById($data['rows'], ['iOperateId' => 'iOperateName'], true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 获取平板型号数据
     *
     * @return mixed
     *
     * create by qgz 20180510
     */
    public function getTabletDataAction(){
        $model = $this->request->getPost('model');
        $sql = "select * from XHIms_Produce where bDelete = 0 AND iPTId = (select iPTId from XHIms_ProduceType where bDelete = 0 AND sType = '平板')";
        $data = $this->db->fetchAll($sql);
        foreach ($data as $value){
            $return['model'][$value['sProdName']] = $value['sProdName'];
            if ($value['sProdName'] == $model){
            	if ($value['iPBId'] !== '' && $value['iPBId'] !== null){
            		$brandName = XHImsBrand::findFirst(['conditions' => 'iPBId = :iPBId:', 'bind' => ['iPBId' => $value['iPBId']]]);
		            $return['Imei'] = $brandName ? $brandName->sBrand : '';
	            }
            }
        }
        return json_encode($return);
    }

    /**
     * 获取品牌数据
     *
     * @return mixed
     *
     * create by qgz 20180510
     */
    public function getBrandDataAction(){
        $model = $this->request->getPost('model');
        $sql = "select sBrand from XHIms_Brand where iPBId = (select iPBId from XHIms_Produce where bDelete=0 AND iPTId = (select iPTId from XHIms_ProduceType where bDelete = 0 AND sType = '平板') AND sProdName = "."'".$model."')";
        $prods = $this->db->fetchAll($sql);
        $return = $prods ? $prods[0]['sBrand'] : null;
        return json_encode($return);
    }

    /**
     * 获取设备用途数据
     *
     * @return string
     *
     * create by qgz 20180619
     */
    public function getPurposeDataAction(){
        return json_encode($this->registerEnum['repairPurposeType']);
    }

    /**
     * 维修项目
     *
     * @return mixed
     *
     * create by qgz 20180514
     */
    public function repairProjectAction(){
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/device/repairProject.js');
        if (!UserPower::checkUserPower('Device_RepairProject')){
            return $this->sendViewError('无查看此页面权限');
        }
        $listSearchArr = $listButtonArr = [];
        if (UserPower::checkUserPower('Device_RepairProject_Add')){
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '添加', 'plain' => 'true', 'icon' => 'fa-plus'];
        }
        if (UserPower::checkUserPower('Device_RepairProject_Del')){
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        if (UserPower::checkUserPower('Device_RepairProject_Edit')){
            $listButtonArr[] = ['id' => 'bt_list_edit', 'text' => '修改', 'plain' => 'true', 'icon' => 'fa-pencil'];
        }
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHSys_RepairProject', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ]);
    }

    /**
     * 获取维修项目金额数据
     *
     * @return mixed
     *
     * create by qgz 20180511
     */
    public function getRepairProjectDataAction(){
        $parameters = [
            'columns' => '*',
            'conditions' => ' bDelete = 0',
        ];
        try{
            $data = Main::runModelPage('Admin\Models\device\XhsysDevicerepairProject', $parameters);
            return $this->sendJsonResponse($data);
        }catch(\Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * 项目创建模块
     *
     *
     * create by qgz 20180515
     */
    public function createProjectAction(){
        Assets::select2();
        Assets::easyUI('js/device/createProjectForm.js');
        $this->view->pick('device/createProjectForm');
        $this->view->setVars([]);
    }

    /**
     * 获取平板型号和名称对
     *
     * @return mixed
     *
     * create by qgz 20180515
     */
    public function getTabletsDataAction(){
        $sql = "select * from XHIms_Produce where bDelete = 0 AND iPTId = (select iPTId from XHIms_ProduceType where bDelete = 0 AND sType = '平板')";
        $data = $this->db->fetchAll($sql);
        foreach ($data as $value){
            $return[$value['iProdId']] = $value['sProdName'];
        }
        return json_encode($return);
    }

    /**
     * 创建收费项目
     *
     * @return mixed
     *
     * create by qgz 20180515
     */
    public function saveProjectDataAction(){
        $postData = $this->request->getPost();
        if ($this->checkEmptyNotZero($postData['prod'])){
	        return $this->sendErrorResponse(400, '请选择型号');
        }
	    if ($this->checkEmptyNotZero($postData['sProjectName'])){
		    return $this->sendErrorResponse(400, '请填写维修项目');
	    }
	    if ($this->checkEmptyNotZero($postData['sProjectPay'])){
		    return $this->sendErrorResponse(400, '请填写金额');//可以填0
	    }
	    if ($this->checkEmptyNotZero($postData['sRemark'])){
		    return $this->sendErrorResponse(400, '请填写备注');
	    }
        $sql = "select * from XHIms_Produce where bDelete = 0 AND iPTId = (select iPTId from XHIms_ProduceType where bDelete = 0 AND sType = '平板') AND iProdId = ".$postData['prod'];
        $data = $this->db->fetchAll($sql);
        if (!$data){
            return $this->sendErrorResponse(500, '暂无数据');
        }
        $params = [
            'columns' => '*',
            'conditions' => 'sTypeName = :sTypeName: AND sProjectName = :sProjectName: AND bDelete = 0',
            'bind' => ['sTypeName' => $data[0]['sProdName'], 'sProjectName' => $postData['sProjectName']]
        ];
        $findData = XhsysDevicerepairProject::findFirst($params);
        if ($findData){
            return $this->sendErrorResponse(400, '该类型已存在该项目');
        }
        $newData = new XhsysDevicerepairProject();
        $newData->iTypeId = $postData['prod'];
        $newData->sTypeName = $data[0]['sProdName'];
        $newData->sProjectName = $postData['sProjectName'];
        $newData->sProjectPay = $postData['sProjectPay'];
        $newData->sRemark = $postData['sRemark'];
        if (!$newData->save()){
            return $this->sendErrorResponse(500, '保存失败');
        }
        return $this->sendSuccessResponse('成功');
    }

	/**
	 * 检查参数是否为空
	 *
	 * @return bool
	 *
	 * create by qgz 20180725
	 */
    public function checkEmptyNotZero($data){
    	if (empty($data) && $data !== 0 && $data !== '0' && $data !== 0.0 ){
    		return true;
	    }
	    return false;
    }

    /**
     * 修改收费项目
     *
     * @return mixed
     *
     * create by qgz 20180517
     */
    public function modifyProjectAction(){
        $postData = $this->request->getPost();
        if (empty($postData) || empty($postData['pay']) || empty($postData['id'])){
            return $this->sendErrorResponse(400, '参数错误');
        }
        $params = [
            'cloumns' => '*',
            'conditions' => 'iId = :iId: AND bDelete = 0',
            'bind' => ['iId' => $postData['id']]
        ];
        $findData = XhsysDevicerepairProject::findFirst($params);
        if (!$findData){
            return $this->sendErrorResponse(500, '不存在该项目数据');
        }
        $findData->sProjectPay = $postData['pay'];
        $findData->sRemark = $postData['remark'];
        if (!$findData->save()){
            return $this->sendErrorResponse(500, '修改出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 删除项目
     *
     * @return mixed
     *
     * create by qgz 20180515
     */
    public function delProjectAction(){
        $ids = $this->request->getPost('ids');
        $ids = implode(',', $ids);
        try{
            $sql = "update XHSys_DeviceRepairProject set bDelete = 1 where bDelete = 0 AND iId in ({$ids})";
            $data = $this->db->execute($sql);
            if (!$data){
                return $this->sendErrorResponse(500, '删除失败');
            }
            return $this->sendSuccessResponse('成功');
        }catch(\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }



    /**
     * 设备申领
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180607
     */
    public function planReceiveListAction()
    {
        $iBPPId = $this->request->getQuery('iBPPId', 'string');
        Assets::easyUI();
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Assets::importJs('js/device/planReceiveList.js');
        $this->view->pick('device/planReceiveList');
        Template::exists('Device_PlanReceive', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (Power::exist('Device_ApplyTab_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_addOther', 'text' => '平板申领', 'icon' => 'fa-tablet');
        }
        if (Power::exist('Device_ApplyTab_StuApply')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '学生机申领', 'icon' => 'fa-tablet');
        }
        if (Power::exist('Device_ApplyTab_Confirm')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_get', 'text' => '确认领用', 'icon' => 'fa-tablet');
        }
        if (Power::exist('Device_ApplyTab_Confirm')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_sign', 'text' => '确认签收', 'icon' => 'fa-tablet');
        }
        if (Power::exist('Device_ApplyTab_Confirm')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_chargeMode', 'text' => '修改收费模式', 'icon' => 'fa-pencil');
        }
        if (Power::exist('Device_ApplyTab_RelatePlan')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_planContact', 'text' => '修改流程关联', 'icon' => 'fa-pencil');
        }
//        if (Power::exist('Device_ApplyTab_Confirm')) {
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_demoConfirm', 'text' => '演示机认证', 'icon' => 'fa-tablet');
//        }
//        if (Power::exist('Device_ReturnTab_Add')) {
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_demoReturn', 'text' => '演示机归还', 'icon' => 'fa-tablet');
//        }
//        if (Power::exist('Device_ApplyTab_Confirm')){
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_print', 'text' => '打印销售单', 'icon' => 'fa-tablet');
//        }
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_pack', 'text'=>'一键收起', 'icon'=>'fa-compress');
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_expand', 'text'=>'一键展开', 'icon'=>'fa-expand');
        if (Power::exist('Device_ApplyTab_Del') || Power::exist('Device_ApplyTab_Confirm')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_print', 'text' => '打印销售单', 'icon' => 'fa-print');

        $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => array_merge([0 => '状态'], self::$planReceiveState), 'default' => 0, 'style' => 'width:100px;' );
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_type', 'data' => array_merge([0 => '类型'], self::$planReceiveType), 'default' => 0, 'style' => 'width:100px;' );
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'school_area', 'style' => 'width: 110px;'];
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if ($iBPPId) {
            $listButtonArr = []; //清除所有的按钮
        }
        return $this->view->setVars([
            'List'       => Template::createList('list', 'Device_PlanReceive', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    public static $planSingeState = [0 => '无需签收', 1 => '待签收', 2 => '已签收'];
    public  static  $planReceiveState = [1 => '待确认' , 2 => '待领用', 3 => '已领用'];
    public static  $planReceiveType = [1 => '流程计划' , 2 => '学生机', 3 => '教师机', 4 =>'备用机', 5 => '公用机' , 6 => '自用机' ];

    /**
     * 学生机申领
     *
     * create by xjq 20180623
     */
    public function studentApplyAction()
    {
        try{
            $iBBPId = $this->request->getQuery('iBPPId', 'string');
            $userId = $this->request->getQuery('userId', 'string');
            if (!$userId) {
                $this->view->pick('device/studentApply');
                Assets::select2();
                Assets::importJs('js/device/studentApply.js');
            } else {
                $this->view->pick('device/studentNoPlan');
                Assets::select2();
                Assets::importJs('js/device/studentNoPlan.js');
                $this->view->setVar('userId', $userId);
                $user = XhsysUser::findFirst([
                    'columns'    => 'sUserName,iSchoolId',
                    'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                    'bind'       => ['iUserId' => $userId]
                ]);
                if (!$user) {
                    return $this->sendViewError('该学生账号未创建');
                }
                $this->view->setVar('userName', $user->sUserName);
                $this->view->setVar('schoolId', $user->iSchoolId);
            }

//            $schools = School::getPower(true);
//            $schools = $schools === true ? School::getSchools() : $schools;
            $tablet = Ims::getProdsByTypeName('平板');
            $tabletShell = Ims::getProdsByTypeName('平板壳');
//            var_dump($schools);die;
            if ($iBBPId) {
                $this->view->setVar('iBBPId', $iBBPId);
                $custId = XHBpmPlan::findFirst($iBBPId)->iCUId;
                $schoolId = Customer::getSchoolId($custId);
                if ($schoolId) {
                    $this->view->setVar('currentSchoolId', $schoolId);
                    $students = XhsysUser::find([
                        'columns'    => 'iUserId, sUserName',
                        'conditions' => 'bDelete = 0 and iUserType = 1 and bDisable = 0 and bHistory = 0 and iSchoolId = :schoolId:',
                        'bind'       => ['schoolId' => $schoolId]
                    ])->toArray();
                    if ($students) {
                        $this->view->setVar('students', array_column($students, 'sUserName', 'iUserId'));
                    }
                }
            }
            $this->view->setVars([
                'planArr' => ProcessPlan::getPlanName(),
                'prod'    => $tablet,
                'mode'    => XhsysEnum::getEnumByNodeName('收费模式'),
                'tabletShell' => $tabletShell,
            ]);
        }catch (XhException $e){
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 归还演示机
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181214
     */
    public function saveRetDemoAction()
    {
        try {
            $iApTabId = $this->request->getPost('iApTabId', 'string');
            $appInfo = XHImsApplyTablet::findFirst($iApTabId);
            if (!$appInfo) {
                return $this->sendErrorResponse(500, '未找到申领记录');
            }
            if ($appInfo->iState != 3  ||  $appInfo->iSignState != 2) {
                return $this->sendErrorResponse(400, '该申领记录不是已归还和已签收状态');
            }
            if ($appInfo->iType != 6 || $appInfo->bDemo != 1) {
                return $this->sendErrorResponse(400, '该记录不是演示机');
            }
            $check = XHImsReturnTab::findFirst([
                'conditions' => 'bDelete= 0 and iApTabId= :iApTabId:',
                'bind'       => ['iApTabId' => $iApTabId],
            ]);
            if ($check) {
                return $this->sendErrorResponse(500, '该演示机记录已发起退还');
            }
            $obj = new XHImsReturnTab();
            $obj->iSource = 4;
            $obj->iState = 2;
            $obj->iApTabId = $iApTabId;
            $getTabArr = $this->db->fetchAll("select t.iUTId,t.iReceivePurpose,t.sDevType,t.sReceiverName,t.sDevNumber,t.iStaffId,u.iUserId,t.iSchoolId,u.sStaffName from XHSys_UserTablet as t left join XHHrm_Staff as u on u.iStaffId = t.iStaffId where t.bDelete = 0 and t.iApTabId = {$iApTabId}");
            if (count($getTabArr) != $appInfo->iTchNum) {
                return $this->sendErrorResponse(500, '演示机数目与授权列表里面的数目对不上');
            }
            $iReceivePurpose = [0 => '自用机', 1 => '备用机', 2 => '学校公用机', 3 => '教师机'];
            Tool::runEnum($getTabArr, ['iReceivePurpose' => $iReceivePurpose]);
            foreach ($getTabArr as $row) {
                if (!$row['sDevType']) {
                    return $this->sendErrorResponse(400, '领用设备类型为空，请确认设备类型在退还入库');
                }
            }
            $obj->mData = $getTabArr;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('归还成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 根据学校id/客户id获取流程计划名称枚举
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181127
     */
    public function ajaxGetPlanNameAction()
    {
        try {
            $schoolId = $this->request->getPost('schoolId', 'int');
            $cuId = $this->request->getPost('cuId', 'int');
            if (!$schoolId && !$cuId ) { //两者取其一
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $data = [];
            if ($cuId) {
                $data = ProcessPlan::getPlanName($cuId);
            }
            if ($schoolId) {
                $data = ProcessPlan::getPlanNameBySchoolId($schoolId);
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 修改申领流程计划关联id
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181127
     */
    public function modifyGetBpmIdAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            $iBPPId = $this->request->getPost('iBPPId', 'int');
            if (!$id || !$iBPPId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHImsApplyTablet::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400, '未找到申领记录');
            }
            $obj->iBPPId = $iBPPId;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 归还修改id
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181211
     */
    public function modifyRetBpmIdAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            $iBPPId = $this->request->getPost('iBPPId', 'int');
            if (!$id || !$iBPPId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHImsReturnTab::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400, '未找到归还记录');
            }
            $obj->iBPPId = $iBPPId;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 根据流程计划id获取学生
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180623
     */
    public function ajaxStuFromPlanAction(){
        try {
            $planId = $this->request->getPost('planId' , 'int');
            if (!$planId) {
                return $this->sendErrorResponse(400 , '缺少参数');
            }
            $plan = XHBpmPlan::findFirst($planId);
            if (!$plan) {
                return $this->sendErrorResponse(400 , '没有找到流程计划记录');
            }
            if (!$plan->iCUId) {
                return $this->sendErrorResponse(400 , '没有找到流程计划关联的客户记录');
            }
            $schoolId = Customer::getSchoolId($plan->iCUId);
            $students = XhsysUser::find([
                'columns'    => 'iUserId , sUserName',
                'conditions' => 'bDelete = 0 and iUserType = 1 and bDisable = 0 and bHistory = 0 and iSchoolId = :schoolId:',
                'bind'       => ['schoolId' => $schoolId]
            ])->toArray();
            if ($students) {
                $students = array_column($students , 'sUserName','iUserId');
            }else{
                $students = [];
            }
            return $this->sendJsonResponse($students);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 修改申请信息
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180803
     */
    public function modifyApTabletAction()
    {
        try {
            $this->view->pick('device/modifyApTablet');
            Assets::importJs('js/device/modifyApTablet.js');
            $id = $this->request->getQuery('id', 'int');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $obj = XHImsApplyTablet::findFirst($id);
            if (!$obj) {
                return $this->sendViewError('不存在该记录');
            }
            $data = $obj->toArray();

            $data['showStu']  = $data['iStuNum'] > 0 ? true : false;
            $data['showShell'] = $data['mTabletShell'] ? true : false;
            $data['showTch']   = $data['mTchCode'] ? true :false;
            $data = [$data];
            Main::runUserNameById($data, ['iCreateUserId' => 'iCreateUserId'], true);
            $data = $data[0];
            if (in_array($data['iType'], [1, 3])){
                $userIds = array_keys($data['mTchCode']);
                if ($userIds) {
                    $user = XhsysUser::find([
                        'columns'    => 'iUserId,sUserName',
                        'conditions' => 'iUserId in ({ids:array})',
                        'bind'       => ['ids' => $userIds]
                    ])->toArray();
                    $tch = array_column($user, 'sUserName', 'iUserId');
                    $this->view->setVar('tch',$tch);
                }
            }
            return $this->view->setVars([
                'info'  => $data,
                'prods' => Ims::getProdsByTypeName('平板'),
                'shell' => Ims::getProdsByTypeName('平板壳'),
                'chargeMode' => XhsysEnum::getEnumByNodeName('收费模式')
            ]);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 修改申领
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180806
     */
    public function saveApModifyAction(){
        try {
            $id   = $this->request->getPost('id', 'int');
            $data = $this->request->getPost();
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少id');
            }
            $obj = XHImsApplyTablet::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400,'该申请未找到');
            }
            $mTabletShell = Tool::getValue($data, 'mTabletShell', null);
            $iProdId = Tool::getValue($data, 'iProdId', null);
            $mTchCode = Tool::getValue($data, 'mTchCode', null);
            $iChargeMode = Tool::getValue($data, 'iChargeMode', null);
            $obj->mTchCode = $mTchCode ?: $obj->mTchCode;
            $obj->iProdId  = $iProdId ?: $obj->iProdId;
            $obj->mTabletShell = $mTabletShell ?: $obj->mTabletShell;
            $obj->iChargeMode = $iChargeMode ?: $obj->iChargeMode;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '修改失败');
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 获取设备
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180607
     */
    public function getPlanReceiveAction(){
        try{
            if (!Power::exist('Device_ApplyTab')) {
                return $this->sendErrorResponse(400 , '缺少权限');
            }
            $key   = $this->request->getPost('key', 'string');
            $state = $this->request->getPost('state', 'int');
            $type  = $this->request->getPost('type', 'int');
            $order = $this->request->getPost('order', 'string');
            $sort  = $this->request->getPost('sort', 'string');
            $iBPPId = $this->request->getPost('iBPPId', 'string');
            $demo   = $this->request->getPost('demo', 'string');
            $school_area = $this->request->getPost('school_area');
            $builder = $this->modelsManager->createBuilder()
                ->from(['Admin\\Models\\ims\\XHImsApplyTablet'])
                ->columns('*')
                ->where('bDelete = 0 ');
            $builder->orderBy('tCreateDate desc');
            if ($key) {
                $machId = School::searchSchool($key, true);
                $matchUserId = User::searchUser($key);
                if ($matchUserId || $machId) {
                    $condition = [];
                    $bind = [];
                    if ($matchUserId) {
                        $condition[] = ' iCreateUserId in ({matchUserIds:array}) ';
                        $bind = array_merge($bind, ['matchUserIds' => $matchUserId]);
                    }
                    if ($machId) {
                        $condition[] = ' iSchoolId in ({matchSchoolIds:array}) ';
                        $bind = array_merge($bind, ['matchSchoolIds' => $machId]);
                    }
                    $builder->andWhere(implode(' or ',$condition), $bind);
                } else {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                }
            }
            if ($state) {
                $builder->andWhere('iState = :iState:', ['iState' => $state]);
            }
            if ($type) {
                $builder->andWhere( 'iType = :iType:', ['iType' => $type]);
            }
            if ($order && $sort) {
                $builder->orderBy( "  {$sort}  {$order} " );
            }
            if ($iBPPId) {
                $builder->andWhere( 'iBPPId = :iBPPId:', ['iBPPId' => $iBPPId]);
            }
            if ($demo) {
                $builder->andWhere('iType = 6 and bDemo = 1 ');
                if (!User::isAdmin()) {
                    $builder->andWhere('iCreateUserId = :iCreateUserId:', ['iCreateUserId' => Main::getLoginUserInfo('userId')]);
                }
            }
            if (!empty($school_area)){
                $depId  = $school_area;
                $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
                $authId = $staff['iUserId'];
                if (!$authId) {
                    return $this->sendErrorResponse(500, '找不到地区部门负责人数据');
                }
                $schoolArr = User::getSchool(true, $authId, true);
                if (!empty($schoolArr)) {
                    $builder->andWhere(' iSchoolId in ({areaSchoolIds:array}) ', ['areaSchoolIds' => array_keys($schoolArr)]);
                }
            }
            //权限模块    自己创建 + 部门额外权限 + 学校列表
            if(!User::isAdmin()){
                $conditionArr = [
                    'conditions' => [],
                    'bind' => []
                ];
                $conditionArr['conditions'][] = ' iCreateUserId = :userId: ';
                $conditionArr['bind'] = ['userId' => Main::getLoginUserInfo('userId')];
                $depArr = User::getExtraPower('dep', 'tabletApply');
                if ($depArr) {
                    $userIds = array_values(array_filter(Hrm::getUserByDepId($depArr, true)));
                    if (count($userIds) > 0) {
                        $conditionArr['conditions'][] = ' iCreateUserId in ({ids:array}) ';
                        $conditionArr['bind'] = array_merge(['ids' => $userIds], $conditionArr['bind']);
                    }
                }
                //学校
                $schoolPower = Power::getExtraPower('school', 'manage', Main::getLoginUserInfo('userId'));
                $schoolPower = $schoolPower === true ? array_keys(School::getSchools()) : $schoolPower;
                if (count($schoolPower) > 0) {
                    $conditionArr['conditions'][] = ' iSchoolId in ({schoolIds:array}) ';
                    $conditionArr['bind'] = array_merge(['schoolIds' => $schoolPower], $conditionArr['bind']);
                }
                $builder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);
            }

            $data = Main::runBuilderPage($builder ,['iState' => self::$planReceiveState , 'iSignState' => self::$planSingeState ] );
            $prodName = XHImsProduce::getProds();
            $mode = XhsysEnum::getEnumByNodeName('收费模式');
            $type = self::$planReceiveType;
            Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName'], true);
            Main::runUserName($data['rows'],['sTeachers' => 'sTeachers' , 'iCreateUserId' => 'iCreateUserId' ,'iLastModifyUserId' => 'iLastModifyUserId','sStudents' => 'sStudents'] , true);
            $cusIdArr = array_values(array_filter(array_column($data['rows'] ,'iCUId')));
            $schoolIdArr = array_values(array_filter(array_column($data['rows'] ,'iSchoolId')));
            $cusInfo = $planArr = $planDataArr = [];
            if ($cusIdArr) {
                $cusInfo = XhcustInfo::find([
                    'columns'    => 'iCUId, sSchoolName',
                    'conditions' => 'bDelete = 0 and iCUId in ({ids:array})',
                    'bind'       => ['ids' => $cusIdArr]
                ])->toArray();
                $cusInfo = array_column($cusInfo, 'sSchoolName', 'iCUId');
            }
            if ($schoolIdArr) {
                $planDataArr = ProcessPlan::getPlanDataBySchoolId($schoolIdArr);
            }
            $planNameArr = array_column(ProcessPlan::getPlanName(), 'name', 'id');

            foreach ($data['rows'] as $index => &$row) {
                switch ($row['iState']) { //1 => '待确认' , 2 => '待领用', 3 => '已领用'
                    case '待确认' :
                        $row['iState'] = '<div class="grid-cell-text-bg-gray">待确认</div>';
                        break;
                    case '待领用' :
                        $row['iState'] = '<div class="grid-cell-text-bg-blue">待领用</div>';
                        break;
                    case '已领用' :
                        $row['iState'] = '<div class="grid-cell-text-bg-green">已领用</div>';
                        break;
                    default :
                        break;
                }
                switch ($row['iSignState']) { //$planSingeState = [0 => '无需签收', 1 => '待签收', 2 => '已签收'];
                    case '无需签收' :
                        $row['iSignState'] = '<div class="grid-cell-text-bg-gray">'.$row['iSignState'].'</div>';
                        break;
                    case '待签收' :
                        $row['iSignState'] = '<div class="grid-cell-text-bg-blue">'.$row['iSignState'].'</div>';
                        break;
                    case '已签收' :
                        $row['iSignState'] = '<div class="grid-cell-text-bg-green">'.$row['iSignState'].'</div>';
                        break;
                    default :
                        break;
                }

                $row['mTchCode'] = $row['mTchCode'] ? unserialize($row['mTchCode']) : [];
                $row['mTchBackInfo'] = $row['mTchBackInfo'] ? unserialize($row['mTchBackInfo']) : [];
                $row['iProdId'] = isset($prodName[$row['iProdId']]) ? $prodName[$row['iProdId']] :'';
                $row['iChargeMode'] = isset($mode[$row['iChargeMode']]) ? $mode[$row['iChargeMode']] :'';
                $row['tchDetail'] = '';
                if (in_array($row['iType'], [1, 3])) {
                    $str = '';
                    if ($row['mTchCode']) {
                        $names = XhsysUser::getUserNameById(array_keys($row['mTchCode']));
                        foreach ($row['mTchCode'] as $tchId => $detail) {
                            $str .= "<tr><td>" . $names[$tchId] . '</td><td>' . $prodName[$detail['iProdId']] . '</td><td>' .$detail['code'] . '</td></tr>';
                        }
                    } else if (strip_tags($row['iSignState']) == '待签收'){
                        $teachers = explode(',',$row['sTeachers']);
                        foreach ($teachers as  $tchName) {
                            $str .= "<tr><td>" . $tchName . '</td><td></td><td></td></tr>';
                        }
                    }
                    $row['tchDetail'] = $str;
                } else if (in_array($row['iType'], [4, 5, 6]) && $row['mTchCode']){
                    $str = '';
                    foreach ($row['mTchCode'] as $tchId => $detail) {
                        $str .= "<tr><td>{$row['iCreateUserId']}</td><td>{$prodName[$detail['iProdId']]}</td><td>{$detail['code']}</td></tr>";
                    }
                    $row['tchDetail'] = $str;
                }
                $row['iType'] = $type[$row['iType']];
                $row['cuId'] = $row['iCUId'];
                if ( $row['iType'] == '自用机' && $row['bDemo'] == 1) {
                    $row['iType'] = '演示机';
                    if ($cusInfo && $row['iCUId']) {
                       $row['iCUId'] = $cusInfo[$row['iCUId']] ?: '';
                    }
                }
                $row['tabletShell'] = unserialize($row['mTabletShell']);
                $str = '';
                if ($row['iProdId']) {
                    $str .= "<tr><td>{$row['iProdId']}</td><td style='text-align: right'>{$row['iStuNum']}</td><td style='text-align: center'>学生机</td></tr>";
                }
                if ($row['mTchBackInfo']) { //有教师直接入库信息
                    foreach ($row['mTchBackInfo'] as $prodDetail) {
                        $str .= "<tr><td>".$prodName[$prodDetail['prodId']]."</td><td style='text-align: right'>".$prodDetail['prodNum']."</td><td style='text-align: center'>". ($row['iType'] == '流程计划' ? '教师机':$row['iType']) ."</td></tr>";
                    }
                } else if ($row['mTchCode']) {
                    $newMergeArr = [];
                    foreach ($row['mTchCode'] as $detail) {
                        $newMergeArr[$detail['iProdId']][] = $detail;
                    }
                    foreach ($newMergeArr as $prodId => $prodDetail) {
                        $str .= "<tr><td>".$prodName[$prodId]."</td><td style='text-align: right'>".count($prodDetail)."</td><td style='text-align: center'>". ($row['iType'] == '流程计划' ? '教师机':$row['iType']) ."</td></tr>";
                    }
                }
                if ($row['tabletShell']) {
                    if (is_array($row['tabletShell'])) {
                        foreach ($row['tabletShell'] as $key => $value){
                            $str .= "<tr><td>{$prodName[$value['prodId']]}</td><td style='text-align: right'>{$value['iNum']}</td><td></td></tr>";
                        }
                    }
                }
                $row['prodDetail'] = $str;
                $row['sPlanName'] = Tool::getValue($planNameArr, $row['iBPPId'], '');
                if ($row['iSchoolId']) {
                    $planNum = count($planDataArr[$row['iSchoolId']]);
                    if ($planNum == 1) {
                        $color = 'green';
                    } else {
                        $color = 'blue';
                    }
                    $row['planNum'] = '<div style="color: ' . $color . '">' . $planNum . '</div>';
                }

//                if ($row['iChargeMode']) {
//                    $row['iChargeMode'] = XhsysEnum::getEnumByNodeName('收费模式')[$row['iChargeMode']];
//                }
            }
            unset($row);

            if ($iBPPId) {
                $confirmStuNum = 0;
                $unConfirmStuNum = 0;
                $confirmTchNum = 0;
                $unConfirmTchNum = 0;
                $confirmBackNum = 0;
                $unConfirmBackNum = 0;
                foreach ($data['rows'] as $row) {
                    if ($row['iType'] == '流程计划') {
                        if (strip_tags($row['iState']) != '已领用') {
                            $unConfirmStuNum += Tool::getValue($row, 'iStuNum', 0);
                            $unConfirmTchNum += Tool::getValue($row, 'iTchNum', 0);
                        } else {
                            $confirmStuNum += Tool::getValue($row, 'iStuNum', 0);
                            $confirmTchNum += Tool::getValue($row, 'iTchNum', 0);
                        }
                    } elseif ($row['iType'] == '教师机') {
                        if (strip_tags($row['iState']) != '已领用') {
                            $unConfirmTchNum += Tool::getValue($row, 'iTchNum', 0);
                        } else {
                            $confirmTchNum += Tool::getValue($row, 'iTchNum', 0);
                        }
                    } elseif ($row['iType'] == '学生机') {
                        if (strip_tags($row['iState']) != '已领用') {
                            $unConfirmStuNum += Tool::getValue($row, 'iStuNum', 0);
                        } else {
                            $confirmStuNum += Tool::getValue($row, 'iStuNum', 0);
                        }
                    } elseif ($row['iType'] == '备用机') {
                        if (strip_tags($row['iState']) != '已领用') {
                            $unConfirmBackNum += Tool::getValue($row, 'iTchNum', 0);
                        } else {
                            $confirmBackNum += Tool::getValue($row, 'iTchNum', 0);
                        }
                    }
                }
                $data['footer'] = [
                    [
                        'iState'    => '已申领学生机',
                        'iType' => $confirmStuNum ,
                        'iStuNum' => '未确认学生机',
                        'iTchNum' => $unConfirmStuNum
                    ],
                    [
                        'iState'    => '已申领教师机',
                        'iType' => $confirmTchNum ,
                        'iStuNum' => '未确认教师机',
                        'iTchNum' => $unConfirmTchNum
                    ],
                    [
                        'iState'    => '已申领备用机',
                        'iType' => $confirmBackNum ,
                        'iStuNum' => '未确认备用机',
                        'iTchNum' => $unConfirmBackNum
                    ],
                ];
            }



//        Main::runUserNameById($data['rows'] , ['iCreateUserId' => 'iCreateUserId' ,'iLastModifyUserId' => 'iLastModifyUserId'] , true);
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 确认签收
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180901
     */
    public function signTabletAction()
    {
        try {
            $iRTId = $this->request->getPost('iRTId', 'int');
            if (!$iRTId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHImsApplyTablet::findFirst($iRTId);
            if (!$obj) {
                return $this->sendErrorResponse(500, '没有该领用id');
            }
            if ($obj->iSignState != 1) {
                return $this->sendErrorResponse(500, '该状态下不需要签收');
            }
            $tchCode = $obj->mTchCode;
            if (!is_array($tchCode)) {
                $tchCode = unserialize($tchCode) ?: [];
            }
            if ($obj->iType != 6) {
                foreach ($tchCode as $index => $row) {  //过滤未认证的老师
                    if (!$row['iProdId'] || !$row['code']){
                        unset($tchCode[$index]);
                    }
                }
                if (count($tchCode) != count(explode(',', $obj->sTeachers))) {
                    return $this->sendErrorResponse(500, '还有老师未存在认证');
                }
            } else { //自用机
                $prodNum = array_column($tchCode, 'code');
                if (count($prodNum) != $obj->iTchNum) {
                    return $this->sendErrorResponse(500, '存在演示机为认证');
                }
            }
            $obj->iSignState = 2 ;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '确认签收失败');
            }
            return $this->sendSuccessResponse('签收成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 其他申请
     *
     * create by xjq 20180704
     */
    public function otherApplyAction(){
        $this->view->pick('device/otherApply');
        Assets::select2();
        Assets::importJs('js/device/otherApply.js');
        $type = self::$planReceiveType;
        $schools = School::getPower(true);
        $schools = $schools === true ? $schools = School::getSchools() : $schools;
        unset($type[1]);unset($type[2]); //流程计划 学生机
        $cusInfo = XhcustInfo::find([
            'columns'    => 'iCUId, sSchoolName',
            'conditions' => 'bDelete = 0'
        ])->toArray();
        $cusInfo = array_column($cusInfo, 'sSchoolName', 'iCUId');
        $this->view->setVars([
            'type'    => $type,
            'schools' => $schools,
            'cusInfo' => $cusInfo,
        ]);
    }

    /**
     * 保存其他申领
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180704
     */
    public function saveOtherApplyAction(){
        try{
            $postData = $this->request->getPost();
            $teachers = $this->request->getPost('sTeachers');
            if (!$postData['iType']) {
                return $this->sendErrorResponse(400 ,'缺少参数');
            }
            if ($postData['sTeachers']) {
                unset($postData['sTeachers']);
            };
            if ($postData['iSchoolId'] && $postData['iType'] == 6) {  //自用机不需要学校
                unset($postData['iSchoolId']);
            }
            $obj = new XHImsApplyTablet();
            if($teachers){
                $obj->sTeachers = implode(',' ,$teachers);
//                if (count($teachers) != $postData['iTchNum']) {
//                    return $this->sendErrorResponse(500, '教师与教师数目不一致');
//                }
            }
            $obj->assign($postData);
            if (!$obj->save()) {
                return $this->sendErrorResponse(500 ,'保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e) {
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 计划领用二维码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180608
     */
    public function planQRAction(){
        $iRTId = $this->request->getPost('iRTId', 'string');
        if (!$iRTId) {
            return $this->sendErrorResponse(400, '缺少领用单号');
        }
        return $this->sendJsonResponse(['msg' => Tool::getQRBase64Uri(Tool::buildUrl('device/scanPlanQR/'.$iRTId.'?userId='.Main::getLoginUserInfo('userId')))]);
    }

    /**
     * 保存学生机申请
     *
     * @param string $tag
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180623
     * modify by xjq 20181217 增加tag非必填项
     */
    public function saveStuApplyAction($tag = '')
    {
        try{
            $postData = $this->request->getPost();
            $students = $this->request->getPost('sStudents');
//            $schoolId = $this->request->getPost('iSchoolId', 'int');
            $iBBPId   = $this->request->getPost('iBBPId', 'int');
            if ($tag != 'noPlan') {
                if (!$iBBPId) {
                    return $this->sendErrorResponse(400, '流程计划未选');
                }
            }

            $obj = new XHImsApplyTablet();
            unset($postData['sStudents']);
            $obj->assign($postData);
            $obj->iState  = 2;
            $obj->iTchNum = 0;
            $obj->iType   = 2;
            $obj->iBPPId  = $iBBPId;
            $obj->sStudents= implode(',' , $students);
            if ($postData['iStuNum'] != count($students)) {
                return $this->sendErrorResponse(500, '学生数目与学生不匹配');
            }
            $custId = XHBpmPlan::findFirst($iBBPId)->iCUId;
            $schoolId = Customer::getSchoolId($custId);
            if ($schoolId) {
                $obj->iSchoolId = $schoolId;
            }
//            $sql = "select c.iSchoolId,p.iBPPId from XHCust_Info as c left join XHBpm_Plan as p on p.iCUId = c.iCUId
//                    where p.bFinish = 0 and p.bDelete = 0 and c.iSchoolId = {$schoolId} order by p.iBPPId desc LIMIT 1";
//            $plan = $this->db->fetchOne($sql);
//            if ($plan && isset($plan['iBPPId'])) {
//                $obj->iBPPId = $plan['iBPPId'];
//            }
            if ($postData['iShellId']) {
                $obj->mTabletShell = [0 => ['prodId' => $postData['iShellId'] , 'iNum' => $postData['iShellNum'] ]];
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            $phones = Main::getConfigByName('ims')['ReceiveSendPhones'];
            if ($phones) {
                $phones = explode(',', $phones);
            }
            $schoolName = XhschoolInfo::getSchoolArray()[$obj->iSchoolId];
            $names = '';
            if ($students) {
                $names = XhsysUser::getUserNameById($students);
                $names = implode(',', array_values($names));
            }
            try {
                foreach ($phones as $phone){
                    $phone = trim($phone);
                    Main::sendSMS($phone, "{$schoolName}的学生机申领,学生：{$names},预计学生平板数目：{$obj->iStuNum}");
                }
            } catch (\Exception $e) {

            } finally {
//                if ($iBBPId) {
//                    $transObj = XHBpmTransList::findFirst([
//                        'conditions' => 'iBPPId = :iBPPId: and bDelete = 0',
//                        'bind'       => ['iBPPId' => $iBBPId]
//                    ]);
//                    if ($transObj) {
//                        $transObj->bUpdate = 1;
//                        if (!$transObj->save()) {
//                            return $this->sendErrorResponse(400, '保存失败');
//                        }
//                    }
//                }
                return $this->sendSuccessResponse('保存成功');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 ,$e->getMessage());
        }
    }


//    public function getOrderNumberAction(){
//        $prefix = 'I0-';
//        $month = date('Y-m');
//
//        $num = $this->db->fetchAll("select count（*）as num from XHIms_ApplyTablet where DATE_FORMAT(tCreateDate,'%Y-%m') = '{$month}'");
//
//    }

    /**
     * 扫码
     *
     * create by xjq 20180608
     */
    public function scanPlanQRAction($iRTId){
        $userId = $this->request->getQuery('userId','int');
        if (!$userId) {
            return $this->sendViewError('获取不到仓库管理员的id');
        }
        try{
            $this->db->begin();
            $obj = XHImsApplyTablet::findFirst($iRTId);
            $type = $obj->iType;
            if (!$obj) {
                return $this->sendViewError('没找到清单');
            }
            if (Main::getLoginUserInfo('userId') != $obj->iCreateUserId) {
                return $this->sendViewError('这个清单不是你的');
            }
            if ($obj->iState != 2 ) {
                return $this->sendViewError( '状态不正确,请等待手机端确认，或改订单已经领用');
            }

            $obj->iState = 3;
            if (!$obj->save()) {
                $this->db->rollback();
                return $this->sendViewError('保存失败');
            }
//            if ($obj->iType == 1 && $obj->iBPPId) {  //流程计划  扫码认证时 自动处理流转单里的数据
//                $this->updateTrans($obj->iBPPId, $obj->toArray());
//            }
//            if ($obj->iType == 2) {
//                $this->updateStuTrans($obj->toArray());
//            }
//            if ($obj->iType == 3) {
//                $this->updateTchTrans($obj->toArray());
//            }
            if (in_array($obj->iType, [1, 2])){ //记录学生机的收费模式
                $this->recordChargeMode($obj->toArray());
            }
            if ($obj->iSignState == 1) {
                //走直接领用入口
                if ($obj->iType == 1) {
                    Ims::prodOut(['iProdId' => $obj->iProdId, 'iOutType' => 2, 'iSchoolId' => $obj->iSchoolId, 'iOutTypeId' => $obj->iRTId, 'iDevType' => 2, 'iOutNum' => $obj->iStuNum], [], '班级直接出库:' . $obj->sClasses, $userId);
                }
                $tchBackInfo = $obj->mTchBackInfo;
//                var_dump($tchBackInfo);die;
                if (!is_array($tchBackInfo)) {
                    $tchBackInfo = unserialize($tchBackInfo) ?: [];
                }
                if ($tchBackInfo){
                    if ($obj->iType == 3) {
                        foreach ($tchBackInfo as $row) {
                            Ims::prodOut(['iProdId' => $row['prodId'] , 'iOutNum' => $row['prodNum'] , 'iSchoolId' => $obj->iSchoolId, 'iOutType' => 2, 'iOutTypeId' => $obj->iRTId,'iDevType' => 3 ], [], '教师机直接出库', $userId);
                        }
                    } elseif ($obj->iType == 6) {
                        foreach ($tchBackInfo as $row) {
                            Ims::prodOut(['iProdId' => $row['prodId'] , 'iOutNum' => $row['prodNum'] , 'iSchoolId' => $obj->iSchoolId, 'iOutType' => 2, 'iOutTypeId' => $obj->iRTId,'iDevType' => 6 ], [], '自用机直接出库', $userId);
                        }
                    }
                } else {
                    if ($obj->iType == 3) { //教师机申领出库
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '没有教师机信息');
                    }
                }
                $shellInfo = $obj->mTabletShell;
                if (!is_array($shellInfo)) {
                    $shellInfo = unserialize($shellInfo) ?: [];
                }
                if ($shellInfo) {
                    foreach ($shellInfo as $row) {
                        Ims::prodOut(['iProdId' => $row['prodId'] , 'iOutNum' => $row['iNum'] , 'iSchoolId' => $obj->iSchoolId, 'iOutType' => 2, 'iOutTypeId' => $obj->iRTId ], [], '平板壳直接出库', $userId);
                    }
                }
                $this->db->commit();
                return $this->sendViewSuccess('直接出库成功');

            }
////            return $this->sendJsonResponse($postData);
//

            $iTypeId = XHImsProduceType::findFirst([
                'columns'     => 'iPTId',
                'conditions'  => 'bDelete = 0 and sType = :sType:',
                'bind'        => ['sType' => '平板']
            ])->iPTId;
            $data = $obj->toArray();
            $data = [$data];
            Main::runUserName(  $data, ['sTeachers' => 'sTeachers' ,'sStudents' => 'sStudents'] , true);
            $data = $data[0];
            if ($type == 1) {
                $mDesc = '产品筹备过程，班级：'. Tool::getValue($data,'sClasses') . ', 教师：'. Tool::getValue($data,'sTeachers') ;
            } else if ($type == 2) {
                $mDesc = '学生机申领，学生：'. Tool::getValue($data,'sStudents');
            } else if ($type == 3) {
                $mDesc = '教师机申领，教师：'. Tool::getValue($data,'sTeachers');
            } else if ($type == 4) {
                $mDesc = '备用机申领';
            } else if ($type == 5) {
                $mDesc = '公用机申领';
            } else if ($type == 6) {
                $mDesc = '自用机申领';
            }

            $staffId = XhhrmStaff::findFirst([
                'columns'    => 'iStaffId',
                'conditions' => 'bDelete = 0 and iUserId =:iUserId:',
                'bind'       => ['iUserId' => $obj->iCreateUserId]
            ]);
            if (!$staffId) {
               return $this->sendErrorResponse(400, '职工账号未绑定');
            }
            $staffId = $staffId->iStaffId;

//            if (Tool::getValue($data , 'iBPPId' ,  '')) { //为流程计划发起的
//                $mDesc = $schools[$data['iSchoolId']] .'的平板申领，班级：'. Tool::getValue($data,'sClasses') . ', 教师：'. Tool::getValue($data,'sTeachers') . '--来自流程计划平板申领' ;
//            }else{
//                $mDesc = $schools[$data['iSchoolId']] .'的平板申领，学生：'. Tool::getValue($data,'sStudents')  . '--来自平板申领学生机申领' ;
//            }
            if ($obj->iStuNum > 0) {
                $data['iTypeId'] = $iTypeId;
//                Ims::resOut($data , ['iOutNum'=>'iStuNum'] , $mDesc , $userId);
                Ims::prodOut($data + ['iOutType' => 2, 'iOutTypeId' => $obj->iRTId ,'iDevType' => 2] , ['iOutNum' => 'iStuNum'], $mDesc , $userId);
            }
            $tchCode = $obj->mTchCode;
            if(!$tchCode) {
                $tchCode = [];
            }
            if (is_string($tchCode)) {
                $tchCode = $tchCode ? unserialize($tchCode) : [];
            }
//            var_dump($tchCode);
//            $this->db->rollback();
//            die;
//            $tchCode = is_string($obj->mTchCode) ? unserialize($obj->mTchCode) : $obj->mTchCode;
            if ($tchCode) {
                if (in_array($type , [1 , 3])) { //流程计划 或者 教师机 类型
                    //合并同类出库
                    $combineArr = [];
                    foreach ($tchCode as $index => $row ) {
                        $combineArr[$row['iProdId']][] = $row;
//                        Device::bindTchTablet($row['code'] , $index , $obj->iSchoolId); //绑定教师机
                        $devType = [['iProdId' => $row['iProdId']]];
                        Ims::runProdNameById($devType, ['iProdId' => 'prodName']);
                        $devType = isset($devType[0]['prodName']) ? $devType[0]['prodName'] : '';
                        $this->bindTablet($row['code'], $type, $index , $obj->iSchoolId, $staffId, $devType);
                    }
                    foreach ($combineArr as $index => $rows){ //教师机合并相同机型的平板后出库
                        Ims::prodOut(['iProdId' => $index , 'iOutNum' => count($rows) , 'iSchoolId' => $obj->iSchoolId, 'iOutType' => 2, 'iOutTypeId' => $obj->iRTId,'iDevType' => 3 ], [], $mDesc , $userId);
//                        Ims::resOut(['iProdId' => $index , 'iOutNum' => count($rows) , 'iSchoolId' => $obj->iSchoolId ] , [] , $mDesc , $userId);
                    }
                } else if (in_array($type, [4, 5, 6])){ //4备用机 公用机 自用机
                    $combineArr = [];
                    foreach ($tchCode as $index => $row ) {
                        $combineArr[$row['iProdId']][] = $row;
                        $devType = [['iProdId' => $row['iProdId']]];
                        Ims::runProdNameById($devType, ['iProdId' => 'prodName']);
                        $devType = isset($devType[0]['prodName']) ? $devType[0]['prodName'] : '';
                        $this->bindTablet($row['code'], $type, $obj->iCreateUserId , $obj->iSchoolId, $staffId, $devType); //自用机  备用机出库
                    }
                    foreach ($combineArr as $index => $rows){ //教师机合并相同机型的平板后出库
                        Ims::prodOut(['iProdId' => $index , 'iOutNum' => count($rows) , 'iSchoolId' => $obj->iSchoolId, 'iOutType' => 2, 'iOutTypeId' => $obj->iRTId, 'iDevType' => $type ], [], $mDesc , $userId);
//                        Ims::resOut(['iProdId' => $index , 'iOutNum' => count($rows) , 'iSchoolId' => $obj->iSchoolId ] , [] , $mDesc , $userId);
                    }
                }
            }
            $shellCode = is_string($obj->mTabletShell) ? unserialize($obj->mTabletShell) : $obj->mTabletShell;
            if ($shellCode){
                foreach ($shellCode as $index => $row ){
                    Ims::prodOut(['iProdId' => $row['prodId'] , 'iOutNum' => $row['iNum'] , 'iSchoolId' => $obj->iSchoolId, 'iOutType' => 2, 'iOutTypeId' => $obj->iRTId ], [], $mDesc , $userId);
//                    Ims::resOut(['iProdId' => $row['prodId'] , 'iOutNum' => $row['iNum'] , 'iSchoolId' => $obj->iSchoolId ] , [] , $mDesc , $userId );
                }
            }

            $this->db->commit();
            return $this->sendViewSuccess('确认领用成功');
        }catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取演示机认证QR
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181213
     */
    public function getDemoConfirmQRAction()
    {
        try {
            $keyId = $this->request->getPost('keyId', 'string');
            if (!$keyId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHImsApplyTablet::findFirst($keyId);
            $pwd = Tool::getValue(Main::getConfigByName('admin'), 'defaultPwd', '123456');
            if (!$obj->sAuthCode) {
                $obj->sAuthCode = substr(md5($obj->iRTId . date('mYd') . $pwd), 0, 30);
                if (!$obj->save()) {
                    throw new \Exception($obj->getError());
                }
            }
            $auth = [
                'account' => 'xuehai'.time(),
                'password' => 'pwd'.time(),
                'code' => 'DEMOAUTHORIZATION:'.$obj->sAuthCode,
                'currentId' => intval(User::getId())
            ];
            return $this->sendJsonResponse(['code' => 200,'msg' => Tool::getQRBase64Uri(json_encode($auth))]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 扫码出库  确认到流程计划的流转单
     *
     * @param $iBPPId
     * @param $dataArr
     *
     * @return bool
     *
     * create by dale  20180906
     */
//    public function updateTrans($iBPPId, $dataArr){
//        $obj = XHBpmTransList::findFirst([
//            'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
//            'bind'       =>  ['iBPPId' => $iBPPId]
//        ]);
//        if (!$obj) {
//            return false;
//        }
//        if ($dataArr['sClasses']) {
//            $classArr = array_values(array_filter(explode(',', $dataArr['sClasses'])));
//        }
//        //copyOldData
//        $arr = [];
//        $arr['sClasses'] = $obj->sClasses;
//        $arr['stuNum'] = $obj->iStudentNum;
//        $arr['tchNum'] = $obj->iTeacherNum;
//        $arr['classNum'] = $obj->iClassNum;
//        $obj->mOldData = json_encode($arr, JSON_UNESCAPED_UNICODE);
//        $obj->bUpdate = 1;
//        $obj->iStudentNum = $dataArr['iStuNum'];
//        $obj->iTeacherNum = $dataArr['iTchNum'];
//        $obj->iClassNum = count($classArr);
//        $obj->sClasses = implode(',', $classArr);
//        if (!$obj->save()) {
//            return false;
//        }
//        return true;
//    }




    /**
     * 记录学生机购置类型
     *
     * @param $tablet
     *
     * @return bool
     *
     * create by dale  20181022
     */
    public function recordChargeMode($tablet)
    {
        if ($tablet['iType'] == 1) {
            if ($tablet['mStuJson']) {
                $studentArr = $tablet['mStuJson'];
                if (is_string($tablet['mStuJson'])) {
                    $studentArr = unserialize($tablet['mStuJson']);
                }
                $studentIdArr = [];
                foreach ($studentArr as $students) {
                    $studentIdArr = array_merge($studentIdArr, $students);
                }
                $studentIdArr = array_values(array_filter(array_unique($studentIdArr)));
                if ($studentIdArr) {
                    if ($tablet['iChargeMode']) {
                        $sql = "update  XHSys_User set iDevSource = {$tablet['iChargeMode']} where  iUserType = 1
                            and  iUserId in (" . implode(',', $studentIdArr) . ") ";
                        $res = $this->db->execute($sql);
                        if (!$res) {
                            $this->createCommitLog('学生购置方式更新失败',['sql' => $sql,'studentIdArr' => $studentIdArr]);
                        }
                    } else {
                        throw new \Exception('收费模式未填写');
                    }
                }
                return true;
            }
        } elseif ($tablet['iType'] == 2) {
            if ($tablet['sStudents']) {
                $studentIdArr = explode(',', $tablet['sStudents']);
                if ($studentIdArr) {
                    if ($tablet['iChargeMode']) {
                        $sql = "update  XHSys_User set iDevSource = {$tablet['iChargeMode']} where  iUserType = 1
                            and  iUserId in (" . implode(',', $studentIdArr) . ") ";
                        $res = $this->db->execute($sql);
                        if (!$res) {
                            $this->createCommitLog('学生购置方式更新失败',['sql' => $sql,'studentIdArr' => $studentIdArr]);
                        }
                        return true;
                    } else {
                        throw new \Exception('收费模式未填写');
                    }
                }
            }
        }
        return true;
    }

    /**
     * 更新学生数目
     *
     * @param $tablet
     *
     * @return bool
     *
     * create by dale  20181011
     */
//    public function updateStuTrans($tablet)
//    {
//        if ($tablet["iSchoolId"]) {
//            $sql = " select p.iBPPId,c.iSchoolId from XHBpm_Plan as p left join XHCust_Info as c on p.iCUId = c.iCUId
//                    where p.bDelete = 0 and p.tCreateDate < '{$tablet["tCreateDate"]}'
//                    and c.iSchoolId = {$tablet["iSchoolId"]} order by p.tCreateDate desc ";
//            $data = $this->db->fetchOne($sql);
//            if ($data) {
//                $iBBPId = Tool::getValue($data, 'iBPPId', null);
//                if ($iBBPId) {
//                    if ($tablet['iRTId']) {
//                        $this->db->execute("update XHIms_ApplyTablet set iBPPId = {$iBBPId} where iRTId = {$tablet['iRTId']} ");
//                    }
//                    $obj = XHBpmTransList::findFirst([
//                        'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
//                        'bind'       => ['iBPPId' => $iBBPId]
//                    ]);
//                    if ($obj) {
//                        if(!$obj->iStudentNum) {
//                            $obj->iStudentNum = 0;
//                        }
//                        $obj->iStudentNum += $tablet['iStuNum'];
//                        $obj->bUpdate = 1;
//                        if ($tablet['sStudents']) {
//                            $classSql = "select sAdClsName from XHSys_User where iUserId in ({$tablet['sStudents']})
//                                  group by sAdClsName ";
//                            $classes = array_column($this->db->fetchAll($classSql), 'sAdClsName');
//                            if ($classes) {
//                                $oldClass = explode(',', $obj->sClasses);
//                                if (!$oldClass) {
//                                    $oldClass = [];
//                                }
//                                $newClass = array_values(array_filter(array_unique(array_merge($oldClass, $classes))));
//                                $obj->sClasses = implode(',', $newClass);
//                            }
//                        }
//                        if (!$obj->save()) {
//                            return false;
//                        }
//                        return true;
//                    }
//
//                }
//            }
//        }
//        return false;
//    }

    /**
     * 更新教师数目
     *
     * @param $tablet
     *
     * @return bool
     *
     * create by dale  20181011
     */
//    public function updateTchTrans($tablet)
//    {
//        if ($tablet["iSchoolId"]) {
//            $sql = " select p.iBPPId,c.iSchoolId from XHBpm_Plan as p left join XHCust_Info as c on p.iCUId = c.iCUId
//                    where p.bDelete = 0 and p.tCreateDate < '{$tablet["tCreateDate"]}'
//                    and c.iSchoolId = {$tablet["iSchoolId"]} order by p.tCreateDate desc ";
//            $data = $this->db->fetchOne($sql);
//            if ($data) {
//                $iBBPId = Tool::getValue($data, 'iBPPId', null);
//                if ($iBBPId) {
//                    if ($tablet['iRTId']) {
//                        $this->db->execute("update XHIms_ApplyTablet set iBPPId = {$iBBPId} where iRTId = {$tablet['iRTId']} ");
//                    }
//                    $obj = XHBpmTransList::findFirst([
//                        'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
//                        'bind'       => ['iBPPId' => $iBBPId]
//                    ]);
//                    if ($obj) {
//                        if(!$obj->iTeacherNum) {
//                            $obj->iTeacherNum = 0;
//                        }
//                        $obj->bUpdate = 1;
//                        $obj->iTeacherNum += $tablet['iTchNum'];
//                        if (!$obj->save()) {
//                            return false;
//                        }
//                        return true;
//                    }
//                }
//            }
//        }
//        return false;
//    }



    /**
     * 绑定机型  自用  备用 公用 教师
     *
     * @param $code
     * @param $tchId
     * @param $type
     * @param $schoolId
     * @param $staffId
     * @param $devType
     * @return bool
     * @throws XhException
     *
     * create by xjq 20180704
     * modify by dale 20180713  添加staffid传入  记录操纵的员工id
     * modify by dale 20180803   备用机 使用完毕
     */
    public function bindTablet($code , $type , $tchId ,$schoolId ,$staffId, $devType){
        if(!$code || !$tchId || !$type){
            throw new XhException('缺少参数');
        }
        $checkTab = XhsysUsertablet::findFirst([
            'conditions' => 'sDevNumber = :sDevNumber: ',
            'bind'       => ['sDevNumber' => $code],
            'order'      => 'iUTId desc'
        ]);

        if($checkTab && !$checkTab->bDelete  && $checkTab->iReceiveStatus  &&  $checkTab->iReceiveStatus != 3){
            throw new XhException('设备号为：'.$code.'的设备未归还无法申请');
        }
        $tablet = new XhsysUsertablet();
        $user = XhsysUser::findFirst($tchId);
        $tablet->sReceiverName    = $user->sUserName;
        $tablet->sReceiverPhone   = $user->sSelfPhone;
        $tablet->sReceiverAccount = $user->sLogonName;
        // 0 自用 1备用  2 公用 4. 教师机
        switch ($type){
            case 1 : $receiveType = 3;break;
            case 3 : $receiveType = 3;break;
            case 4 : $receiveType = 1;break;
            case 5 : $receiveType = 2;break;
            case 6 : $receiveType = 0;break;
            default: $receiveType = 0;
        }
        $tablet->iReceiveStatus   = 2;
        $tablet->iReceivePurpose  = $receiveType;
        if ($receiveType == 1) { //备用机使用完毕
            $tablet->bDone  = 1 ;
        }
        $tablet->iSchoolId        = $schoolId;
        $tablet->sDevNumber       = $code;
        $tablet->iStaffId         = $staffId;
        $tablet->tReceiveTime     = date('Y-m-d H:i:s',time());
        $tablet->sDevType         = $devType ?: '';
        if(!$tablet->save()){
            throw new XhException('绑定设备失败');
        }
        return true;
    }

    /**
     * 删除成功
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180612
     */
    public function delApplyAction(){
        try{
            $id = $this->request->getPost('id' , 'int');
            $obj = XHImsApplyTablet::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(500 , '未找到对应的领用记录');
            }

            if (User::isAdmin() ||
                ($obj->iCreateUserId == Main::getLoginUserInfo('userId') && $obj->iState != 3) ||
                Power::exist('Device_ApplyTab_Confirm')) {
                $obj->bDelete = 1;
            } else {
                return $this->sendErrorResponse(401 ,'没有权限');
            }

            if (!$obj->save()) {
                return $this->sendErrorResponse('删除失败');
            }
            return $this->sendSuccessResponse('删除成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse( 500  , $e->getMessage());
        }
    }

    public static $tabReturnSource = [1 => '设备领用', 2 => '学生管理', 3 =>'教师管理',4 => '申领列表'];
    public static $tabReturnState   = [1 => '待确认' , 2 => '待归还', 3 => '已归还'];

    /**
     * 平板退还
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180727
     */
    public function tabReturnAction(){
        if (!Power::exist('Device_ReturnTab')) {
            return $this->sendViewError('没有权限');
        }
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('', true);
        $this->view->pick('device/tabReturn');
        Assets::importJs('js/device/tabReturn.js');
        $listSearchArr = $listButtonArr = [];
        if (Power::exist('Device_ReturnTab_Confirm')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_scanQR', 'text' => '确认扫码', 'icon' => 'fa-plus');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_scanBatchQR', 'text' => '批量确认', 'icon' => 'fa-plus');
        }
        if (Power::exist('Device_ReturnTab_RelatePlan')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_planContact', 'text' => '修改流程关联', 'icon' => 'fa-pencil');
        }
        if (Power::exist('Device_ReturnTab_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_pack', 'text'=>'一键收起', 'icon'=>'fa-compress');
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_expand', 'text'=>'一键展开', 'icon'=>'fa-expand');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_source',
            'data' => array_merge([0 => '——来源——'], self::$tabReturnSource), 'default' => 0, 'style' => 'width:100px;');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_states',
            'data' => array_merge([0 => '归还状态'], self::$tabReturnState), 'default' => 0, 'style' => 'width:100px;');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ','style' => 'width:100px !important;');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'          => Template::createList('list', 'Device_TabReturn', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取平板归还
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180728
     */
    public function getTabReturnAction(){
        try {
            if (!Power::exist('Device_ReturnTab')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $source = $this->request->getPost('source','int');
            $key = $this->request->getPost('key','string');
            $states = $this->request->getPost('states', 'string');
            $iBPPId = $this->request->getPost('iBPPId', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->from(['Admin\\Models\\ims\\XHImsReturnTab'])
                ->where('bDelete = 0');
            if ($source) {
                $builder->andWhere('iSource = :source:', ['source' => $source]);
            }
            if ($states) {
                $builder->andWhere('iState = :iState:', ['iState' => $states]);
            }
            if ($key) {
                $conditionArr = [
                    'conditions' => ['mDesc like :key: or mSourceName like :key:'],
                    'bind'       => ['key' => '%' . $key . '%']
                ];
                $schoolIds = School::searchSchool($key, true);
                if ($schoolIds) {
                    $conditionArr['conditions'][] = ' iSchoolId in ({ids:array}) ';
                    $conditionArr['bind'] =  array_merge($conditionArr['bind'], ['ids' => $schoolIds]);
                }
                $builder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);
            }
            if ($iBPPId) {
                $builder->andWhere('iBPPId = :iBPPId:', ['iBPPId' => $iBPPId]);
            }
            if (!User::isAdmin() && !Power::exist('Device_ReturnTab_Confirm')) {
                $ids[] = Main::getLoginUserInfo('userId');
                $depArr = User::getExtraPower('dep', 'tabletReturn');
                if ($depArr) {
                    $userIds = Hrm::getUserByDepId($depArr, true);
                    if (count($userIds) > 0) {
                        $ids = array_merge($ids, $userIds);
                    }
                }
                $builder->andWhere('iCreateUserId in ({ids:array})', ['ids' => $ids]);
            }
            $builder->orderBy('tCreateDate desc');
            $data = Main::runBuilderPage($builder ,['iState' => self::$tabReturnState]);
            $source = self::$tabReturnSource;
            $schoolNames = XhschoolInfo::getSchoolArray();
            $planNameArr = array_column(ProcessPlan::getPlanName(), 'name', 'id');
            foreach ($data['rows'] as &$row) {
                switch ($row['iState']) { //1 => '待确认' , 2 => '待领用', 3 => '已领用'
                    case '待确认' :
                        $row['iState'] = '<div class="grid-cell-text-bg-gray">待确认</div>';
                        break;
                    case '待归还' :
                        $row['iState'] = '<div class="grid-cell-text-bg-blue">待归还</div>';
                        break;
                    case '已归还' :
                        $row['iState'] = '<div class="grid-cell-text-bg-green">已归还</div>';
                        break;
                    default :
                        break;
                }
                $row['source'] = $source[$row['iSource']];
                $row['mData'] = $row['mData'] ? unserialize($row['mData']) : [];
                $row['total'] = [];
                $total = [];
                if ($row['mData']) {
                   Main::runUserName($row['mData'], ['iUserId' => 'sUserName'], false);
                   foreach ($row['mData'] as &$values) {
                       $values['sSchoolName'] = isset($schoolNames[$values['iSchoolId']]) ? $schoolNames[$values['iSchoolId']] : '';
                       $total[$values['sDevType']][] = $values;
                   }
                   unset($values);
                   if ($total) {
                       foreach ($total as $name => $record) {
                           $row['total'][] = ['name' => $name, 'num' => count($record)];
                       }
                   }
                }
                $row['sSchoolName'] = Tool::getValue($schoolNames, $row['iSchoolId'], '');
                $row['sPlanName'] = Tool::getValue($planNameArr, $row['iBPPId'], '');
            }
            unset($row);
            Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' =>'iLastModifyUserId'], true);
            if ($iBPPId) {
                $confirmStuNum = 0;
                $unConfirmStuNum = 0;
                $confirmTchNum = 0;
                $unConfirmTchNum = 0;
                $confirmBackNum = 0;
                $unConfirmBackNum = 0;
                foreach ($data['rows'] as $row) {
                    if ($row['source'] == '教师管理') {
                        if (strip_tags($row['iState']) != '已归还') {
                            $unConfirmTchNum += count($row['mData']);
                        } else {
                            $confirmTchNum += count($row['mData']);
                        }
                    } elseif ($row['source'] == '学生管理') {
                        if (strip_tags($row['iState']) != '已归还') {
                            $unConfirmStuNum += count($row['mData']);
                        } else {
                            $confirmStuNum += count($row['mData']);
                        }
                    } elseif ($row['source'] == '设备领用') {
                        if (strip_tags($row['iState']) != '已归还') {
                            foreach ($row['mData'] as $indexRow) {
                                $devType = Tool::getValue($indexRow, 'iReceivePurpose', '');
                                if ($devType) {
                                    $unConfirmTchNum += $devType == '教师机' ? 1 : 0;
                                    $unConfirmBackNum += $devType == '备用机' ? 1 : 0;
                                }
                            }
                        } else {
                            foreach ($row['mData'] as $indexRow) {
                                $devType = Tool::getValue($indexRow, 'iReceivePurpose', '');
                                if ($devType) {
                                    $confirmTchNum += $devType == '教师机' ? 1 : 0;
                                    $confirmBackNum += $devType == '备用机' ? 1 : 0;
                                }
                            }
                        }
                    }
                }
                $data['footer'] = [
                    [
                        'iState'    => '已归还学生机',
                        'source' => $confirmStuNum ,
                        'mDesc' => '未确认学生机',
                        'tCreateDate' => $unConfirmStuNum
                    ],
                    [
                        'iState'    => '已归还教师机',
                        'source' => $confirmTchNum ,
                        'mDesc' => '未确认教师机',
                        'tCreateDate' => $unConfirmTchNum
                    ],
                    [
                        'iState'    => '已归还备用机',
                        'source' => $confirmBackNum ,
                        'mDesc' => '未确认备用机',
                        'tCreateDate' => $unConfirmBackNum
                    ],
                ];
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存设备归还申请
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180728
     * modify by ck 20180829
     */
    public function saveReturnTabAction(){
        try {
            if (!Power::exist('Device_ReturnTab_Add')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $data = $this->request->getPost();
            if (in_array($data['iSource'], [2, 3]) && !$data['iBPPId']) {
                return $this->sendErrorResponse(400, '教师机，学生机归还教师必选流程计划id');
            }
            $sourceIds = $this->request->getPost('sSourceIds','string');
            $obj = new XHImsReturnTab();
            $obj->assign($data);
            $obj->iState = 2;
            $sourceIds = array_values(array_filter(explode(',', $sourceIds)));
            if (!$sourceIds) {
                return $this->sendErrorResponse(400, '目标id不存在');
            }
            $iReceivePurpose = [0 => '自用机', 1 => '备用机', 2 => '学校公用机', 3 => '教师机'];
            if ($obj->iSource == 1) { //领用列表
                $purpose = $this->db->fetchAll("select DISTINCT(iReceivePurpose) as purpose from XHSys_UserTablet where bDelete = 0 and iUTId in (".implode(',', $sourceIds).")  ");
                if (count($purpose) > 1) {
                    return $this->sendErrorResponse('所选机型不属于同一类型无法提交');
                }
                $checkReturn = XhsysUsertablet::count([
                    'conditions' => 'bDelete = 0 and iUTId in ({ids:array}) and iReceiveStatus = 3',
                    'bind'       => ['ids' => $sourceIds]
                ]);
                if ($checkReturn) {
                    return $this->sendErrorResponse(400, '存在设备已经归还');
                }

                $purpose = $purpose[0]['purpose'];
                if($purpose == 3){ //教师机
                    if (!$obj->iBPPId) {
                        return $this->sendErrorResponse(400, '教师机退还流程计划必选');
                    }
                    $getTabArr = $this->db->fetchAll("select t.iUTId,t.iReceivePurpose,t.sDevType,t.sReceiverName,t.sDevNumber,t.sReceiverAccount,u.iUserId,t.iSchoolId,u.sUserName from XHSys_UserTablet as t left join XHSys_User as u on u.sLogonName = t.sReceiverAccount  where t.bDelete = 0 and t.iUTId in (".implode(',', $sourceIds).") ");
                }else if (in_array($purpose, [1, 2])) {
                    $getTabArr = $this->db->fetchAll("select t.iUTId,t.iReceivePurpose,t.sDevType,t.sReceiverName,t.sDevNumber,t.sReceiverPhone,u.iUserId,t.iSchoolId,u.sUserName from XHSys_UserTablet as t left join XHSys_User as u on u.sSelfPhone = t.sReceiverPhone where t.bDelete = 0 and t.iUTId in (".implode(',', $sourceIds).") ");
                } else if ($purpose == 0) {
                    $getTabArr = $this->db->fetchAll("select t.iUTId,t.iReceivePurpose,t.sDevType,t.sReceiverName,t.sDevNumber,t.iStaffId,u.iUserId,t.iSchoolId,u.sStaffName from XHSys_UserTablet as t left join XHHrm_Staff as u on u.iStaffId = t.iStaffId where t.bDelete = 0 and t.iUTId in (".implode(',', $sourceIds).") ");
                } else {
                    return $this->sendErrorResponse(500, '未知类型');
                }
                Tool::runEnum($getTabArr, ['iReceivePurpose' => $iReceivePurpose]);

                foreach ($getTabArr as $row) {
                    if (!$row['sDevType']) {
                        return $this->sendErrorResponse(400, '领用设备类型为空，请确认设备类型在退还入库');
                    }
                }
                $obj->mData = $getTabArr;
            } else if ($obj->iSource == 2) { //学生列表
                $bindArr = $this->db->fetchAll("select t.iADLId,t.iUserId,u.sUserName,t.sDeviceNumber as sDevNumber,t.sModel as sDevType,u.iSchoolId from XHSys_AccountDeviceLocked as t left join XHSys_User as u on t.iUserId = u.iUserId where t.bDelete = 0 and t.iUserId in (".implode(',', $sourceIds).") ");
                if (!$bindArr) {
                   return $this->sendErrorResponse(400, '所选的学生不存在绑定记录');
                }
                $count = count($bindArr);
                if ($count != count(array_values(array_filter(array_unique(array_column($bindArr, 'iUserId')))))){
                    return $this->sendErrorResponse(500, '存在学生绑定多个设备，请去领用列表退还设备');
                }
                foreach ($bindArr as $row) {
                    if (!$row['sDevType']) {
                        if ($row['sUserName']) {
                            return $this->sendErrorResponse(400, $row['sUserName'].'绑定设备类型为空，请确认设备类型在退还入库');
                        } else {
                            return $this->sendErrorResponse(400, '绑定设备类型为空，请确认设备类型在退还入库');
                        }
                    }
                }
                $obj->mData = $bindArr;
            } else if ($obj->iSource == 3) { //教师列表
                $bindArr = $this->db->fetchAll("select t.iADLId,t.iUserId,u.sUserName,t.sDeviceNumber as sDevNumber,t.sModel as sDevType,u.iSchoolId from XHSys_AccountDeviceLocked as t left join XHSys_User as u on t.iUserId = u.iUserId where t.bDelete = 0 and t.iUserId in (".implode(',', $sourceIds).") ");
                $getTabArr = $this->db->fetchAll("select t.iUTId,t.iReceivePurpose,t.sDevType,t.sDevNumber,t.sReceiverAccount,t.sReceiverName,u.iUserId,u.sUserName,t.iSchoolId from XHSys_UserTablet as t left join XHSys_User as u on u.sLogonName = t.sReceiverAccount where t.bDelete = 0 and u.iUserId in (".implode(',', $sourceIds).") ");
                $count = count($bindArr);
                if ($count != count(array_values(array_filter(array_unique(array_column($bindArr, 'iUserId')))))){
                    return $this->sendErrorResponse(500, '存在教师绑定多个设备，请去领用列表退还设备');
                }
                $mergeArr = [];
                if (!$getTabArr && !$bindArr) {
                    return $this->sendErrorResponse(400, '所选教师没有绑定且领用记录');
                }
                if ($getTabArr) {
                    Tool::runEnum($getTabArr, ['iReceivePurpose' => $iReceivePurpose]);
                    foreach ($getTabArr as $row) {
                        $mergeArr[$row['sDevNumber']] = $row;
                        $mergeArr[$row['sDevNumber']]['bBind']   = false;
                        $mergeArr[$row['sDevNumber']]['bGetTab'] = true;
                    }
                }
                if ($bindArr) {
                    foreach ($bindArr as $row) {
                        if (isset($mergeArr[$row['sDevNumber']])) {
                            $mergeArr[$row['sDevNumber']]['bBind']    = true;
                            $mergeArr[$row['sDevNumber']]['iADLId']   = $row['iADLId'];
                            $mergeArr[$row['sDevNumber']]['sDevType'] = isset($mergeArr[$row['sDevNumber']]['sDevType']) ? $mergeArr[$row['sDevNumber']]['sDevType'] : $row['sDevType'];
                        } else {
                            $mergeArr[$row['sDevNumber']] = $row;
                            $mergeArr[$row['sDevNumber']]['bBind']   = true;
                            $mergeArr[$row['sDevNumber']]['bGetTab'] = false;
                        }
                    }
                }
                foreach ($mergeArr as $row) {
                    if (!$row['sDevType']) {
                        $user = XhsysUser::findFirst($row['iUserId'])->sUserName;
                        if ($row['bGetTab']) {
                            return $this->sendErrorResponse(400, $user.'领用设备类型为空，请确认设备类型在退还入库');
                        } else if ($row['bBind']) {
                            return $this->sendErrorResponse(400 ,$user.'绑定设备类型为空，请确认设备类型在退还入库');
                        }
                    }
                }
                $obj->mData = array_values($mergeArr);
            } else {
                return $this->sendErrorResponse(400, '错误类型');
            }
            $obj->mSourceName = implode(',', array_values(array_filter(array_column($obj->mData , 'sUserName'))));
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 演示机申领
     *
     * @return View|string
     *
     * create by dale  20181217
     */
    public function demoApplyListAction()
    {
        try {
            $iBPPId = $this->request->getQuery('iBPPId', 'string');
            Assets::easyUI();
            Assets::importMainJs('assets/easyui/datagrid-detailview.js');
            Assets::importJs('js/device/demoApplyList.js');
            $this->view->pick('device/planReceiveList');
            Template::exists('Device_PlanReceive', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            if (Power::exist('Device_ReturnTab_Add')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_demoReturn', 'text' => '演示机归还', 'icon' => 'fa-tablet');
            }
            $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_pack', 'text'=>'一键收起', 'icon'=>'fa-compress');
            $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_expand', 'text'=>'一键展开', 'icon'=>'fa-expand');
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => array_merge([0 => '状态'], self::$planReceiveState), 'default' => 0, 'style' => 'width:100px;' );
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_type', 'data' => array_merge([0 => '类型'], self::$planReceiveType), 'default' => 0, 'style' => 'width:100px;' );
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
            if ($iBPPId) {
                $listButtonArr = []; //清除所有的按钮
            }
            return $this->view->setVars([
                'List'       => Template::createList('list', 'Device_PlanReceive', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
                ]),
                'demoList' => true,
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     *  修改入库平板
     *
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180904
     */
    public function modifyRetTabletAction()
    {
        try {
            $iRTId = $this->request->getQuery('iRTId', 'int');
            $this->view->pick('device/modifyRetTablet');
            Assets::importJs('js/device/modifyRetTablet.js');
            $info = XHImsReturnTab::findFirst($iRTId)->toArray();
            $info['mData'] = is_string($info['mData']) ? unserialize($info['mData']) : $info['mData'];
            $totalRecord = '';
            $total = [];
            if ($info['mData']) {
                foreach ($info['mData'] as $index => $row) {
                    $total[$row['sDevType']][] = $row;
                }
                foreach ($total as $name => $record) {
                    $totalRecord .= "{$name}共" . count($record) ."台;";
                }
            }
            return $this->view->setVars([
                'prod' => Ims::getProdsByTypeName('平板'),
                'info' => $info,
                'totalRecord' => $totalRecord
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError( $e->getMessage());
        }
    }

    /**
     * 保存修改成功
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180904
     */
    public function saveModifyRetTabletAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            $data = $this->request->getPost('mData');
            if (!$id || !$data){
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $tab = XHImsReturnTab::findFirst($id);
            if (!$tab) {
                return $this->sendErrorResponse(500, '没有该记录');
            }
            $tab->mData = $data;
            if (!$tab->save()) {
                return $this->sendErrorResponse(500, '平板类型修改失败');
            }
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取归还二维码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180801
     */
    public function getReturnTabQRAction(){
        $iRTId = $this->request->getPost('iRTId', 'string');
        if (!$iRTId) {
            return $this->sendErrorResponse(400, '缺少归还单号');
        }
        return $this->sendJsonResponse(['msg' => Tool::getQRBase64Uri(Tool::buildUrl('device/scanReturnQR/'.$iRTId.'?userId='.Main::getLoginUserInfo('userId')))]);
    }


    /**
     * 扫描归还二位码
     *
     * @param $iRTId
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180801
     */
    public function scanReturnQRAction($iRTId){
        try {
            $this->db->begin();
            $userId = $this->request->getQuery('userId');
            $obj = XHImsReturnTab::findFirst($iRTId);
            if (!$obj) {
                return $this->sendViewError( '未找到该清单');
            }
            if ($obj->iCreateUserId !=  Main::getLoginUserInfo('userId')) {
                return $this->sendViewError( '该单号不属于你');
            }
            if ($obj->iState == 3) {
                return $this->sendViewError( '该单号已经领用请不要重复操作');
            }
            $obj->iState = 3;
            if (!$obj->save()) {
                $this->db->rollback();
                return $this->sendViewError('单号状态修改失败');
            }
            $data = $obj->mData;
            if(!is_array($data)) { //如果没有转化
                $data = $data ? unserialize($data) : [];
            }

            Main::runUserName($data, ['iUserId' => 'sUserName'], false);
            Ims::runProdIdByName($data, ['sDevType' => 'iProdId']);
            $this->retTablet($data, $userId, $obj->iSource, $obj->iRTId);
//            if ($data) {
//                //设备解绑 归还
//                $ids = array_values(array_filter(array_column($data, 'iADLId')));
//                if ($ids) {
//                    $bindObjArr = XhsysAccountdevicelocked::find([
//                        'conditions' => 'bDelete = 0 and iADLId in ({ids:array})',
//                        'bind'       => ['ids' => $ids]
//                    ]);
//                    foreach ($bindObjArr as $bindObj) {
//                        if (!$bindObj->delete()) {
//                            $this->db->rollback();
//                            return $this->sendViewError('解绑失败');
//                        }
//                    }
//                }
//                if ($obj->iSource == 1) { //领用列表
//                    $codes = array_values(array_filter(array_column($data , 'sDevNumber')));
//                    if($codes) {
//                        $getObjArr = XhsysUsertablet::find([
//                            'conditions' => 'bDelete = 0 and sDevNumber in ({codes:array})',
//                            'bind' => ['codes' => $codes]
//                        ]);
//                        foreach ($getObjArr as $getObj) {
//                            $getObj->bDone = 1;
//                            $getObj->iReceiveStatus = 3;
//                            if (!$getObj->save()) {
//                                $this->db->rollback();
//                                return $this->sendViewError('领用归还失败');
//                            }
//                        }
//                    }
//                    //直接入库
//                    foreach ($data as $row) {
//                        if (!$row['iProdId']) {
//                            $this->db->rollback();
//                            return $this->sendViewError('设备类型未知');
//                        }
//                        if ($row['iReceivePurpose'] == '教师机') {
//                            Ims::prodIn(['iProdId' =>$row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' =>$obj->iRTId, 'iDevType' => 3 ,'iSchoolId' => $row['iSchoolId'] ],[],'领用退还入库，教师:'.$row['sUserName'], $userId);
//                        } else if ($row['iReceivePurpose'] == '学生机') {
//                            Ims::prodIn(['iProdId' =>$row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' =>$obj->iRTId, 'iDevType' => 2,'iSchoolId' => $row['iSchoolId'] ],[],'领用退还入库，学生:'.$row['sUserName'], $userId);
//                        } else if ($row['iReceivePurpose'] == '备用机') {
//                            Ims::prodIn(['iProdId' =>$row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' =>$obj->iRTId, 'iDevType' => 4,'iSchoolId' => $row['iSchoolId'] ],[],'领用退还入库，领用人:'.$row['sReceiverName'], $userId);
//                        } else if ($row['iReceivePurpose'] == '学校公用机') {
//                            Ims::prodIn(['iProdId' =>$row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' =>$obj->iRTId, 'iDevType' => 5,'iSchoolId' => $row['iSchoolId'] ],[],'领用退还入库，领用人:'.$row['sReceiverName'], $userId);
//                        } else if ($row['iReceivePurpose'] == '自用机') {
//                            Ims::prodIn(['iProdId' =>$row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' =>$obj->iRTId, 'iDevType' => 6,'iSchoolId' => $row['iSchoolId'] ],[],'领用退还入库，领用人:'.$row['sReceiverName'], $userId);
//                        } else {
//                            return $this->sendViewError('未知机型');
//                        }
//                    }
//                } else if ($obj->iSource == 2) { //学生列表
//                    //合并入库
//                    $mergeArr = [];
//                    foreach ($data as $row) {
//                        $mergeArr[$row['iProdId']][] = $row;
//                    }
//                    foreach ($mergeArr as $index => $row) {
//                        $students = implode(',', array_column($row, 'sUserName'));
//                        Ims::prodIn(['iProdId' =>$index, 'iInNum' => count($row), 'iInType' =>2, 'iInTypeId' =>$obj->iRTId, 'iDevType' => 2 ,'iSchoolId' => $row[0]['iSchoolId'] ],[],'学生机退还入库，学生:'.$students, $userId);
//                    }
//                } else if ($obj->iSource == 3){ //教师
//                    $getIds = array_values(array_filter(array_column($data, 'iUTId')));
//                    if ($getIds) {
//                        $getObjArr = XhsysUsertablet::find([
//                            'conditions' => 'bDelete = 0 and iUTId in ({ids:array})',
//                            'bind' => ['ids' => $getIds]
//                        ]);
//                        foreach ($getObjArr as $getObj) {
//                            $getObj->bDone = 1;
//                            $getObj->iReceiveStatus = 3;
//                            if (!$getObj->save()) {
//                                $this->db->rollback();
//                                return $this->sendViewError( '领用归还失败');
//                            }
//                        }
//                    }
//                    //合并入库
//                    $mergeArr = [];
//                    foreach ($data as $row) {
//                        $mergeArr[$row['iProdId']][] = $row;
//                    }
//                    foreach ($mergeArr as $index => $row) {
//                        $teachers = implode(',', array_column($row, 'sUserName'));
//                        Ims::prodIn(['iProdId' =>$index, 'iInNum' => count($row), 'iInType' =>2, 'iInTypeId' =>$obj->iRTId, 'iDevType' => 3 ,'iSchoolId' => $row[0]['iSchoolId'] ],[],'教师机退还入库，教师:'.$teachers, $userId);
//                    }
//                } else {
//                    return $this->sendViewError('未知来源');
//                }
//            }
            $this->db->commit();
            return $this->sendViewSuccess('归还成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }


    /**
     * 归还设备
     *
     * @param $data
     * @param $userId
     * @param $source
     * @param $iRTId
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20181026
     */
    private function retTablet($data, $userId, $source,$iRTId)
    {
        if (!$data || !$userId) {
            throw new XhException('缺少必要参数表userId或者数据源缺失');
        }
        //设备解绑 归还
        $ids = array_values(array_filter(array_column($data, 'iADLId')));
        if ($ids) {
            $bindObjArr = XhsysAccountdevicelocked::find([
                'conditions' => 'bDelete = 0 and iADLId in ({ids:array})',
                'bind' => ['ids' => $ids]
            ]);
            foreach ($bindObjArr as $bindObj) {
                if (!$bindObj->delete()) {
                    throw new XhException('解绑失败');
                }
            }
        }
        if ($source == 1) { //领用列表
            $codes = array_values(array_filter(array_column($data, 'sDevNumber')));
            if ($codes) {
                $getObjArr = XhsysUsertablet::find([
                    'conditions' => 'bDelete = 0 and sDevNumber in ({codes:array})',
                    'bind' => ['codes' => $codes]
                ]);
                foreach ($getObjArr as $getObj) {
                    $getObj->bDone = 1;
                    $getObj->iReceiveStatus = 3;
                    if (!$getObj->save()) {
                        throw new XhException('领用归还失败');
                    }
                    $bindObj = XhsysAccountdevicelocked::find([
                        'conditions' => 'bDelete = 0 and sDeviceNumber = :sDeviceNumber:',
                        'bind' => ['sDeviceNumber' => $getObj->sDevNumber]
                    ]);
                    if ($bindObj) { //如果有绑定记录 直接解绑
                        if (!$bindObj->delete()) {
                            throw new XhException('解绑失败');
                        }
                    }
                }
            }
            //直接入库
            foreach ($data as $row) {
                if (!$row['iProdId']) {
                    throw new XhException('设备类型未知');
                }
                if ($row['iReceivePurpose'] == '教师机') {
                    Ims::prodIn(['iProdId' => $row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 3, 'iSchoolId' => $row['iSchoolId']], [], '领用退还入库，教师:' . $row['sUserName'], $userId);
                } else if ($row['iReceivePurpose'] == '学生机') {
                    Ims::prodIn(['iProdId' => $row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 2, 'iSchoolId' => $row['iSchoolId']], [], '领用退还入库，学生:' . $row['sUserName'], $userId);
                } else if ($row['iReceivePurpose'] == '备用机') {
                    Ims::prodIn(['iProdId' => $row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 4, 'iSchoolId' => $row['iSchoolId']], [], '领用退还入库，领用人:' . $row['sReceiverName'], $userId);
                } else if ($row['iReceivePurpose'] == '学校公用机') {
                    Ims::prodIn(['iProdId' => $row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 5, 'iSchoolId' => $row['iSchoolId']], [], '领用退还入库，领用人:' . $row['sReceiverName'], $userId);
                } else if ($row['iReceivePurpose'] == '自用机') {
                    Ims::prodIn(['iProdId' => $row['iProdId'], 'iInNum' => 1, 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 6, 'iSchoolId' => $row['iSchoolId']], [], '领用退还入库，领用人:' . $row['sReceiverName'], $userId);
                } else {
                    throw new XhException('未知机型');
                }
            }
        } else if ($source == 2) { //学生列表
            //合并入库
            $mergeArr = [];
            foreach ($data as $row) {
                $mergeArr[$row['iProdId']][] = $row;
            }
            foreach ($mergeArr as $index => $row) {
                $students = implode(',', array_column($row, 'sUserName'));
                Ims::prodIn(['iProdId' => $index, 'iInNum' => count($row), 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 2, 'iSchoolId' => $row[0]['iSchoolId']], [], '学生机退还入库，学生:' . $students, $userId);
            }
        } else if ($source == 3) { //教师
            $getIds = array_values(array_filter(array_column($data, 'iUTId')));
            if ($getIds) {
                $getObjArr = XhsysUsertablet::find([
                    'conditions' => 'bDelete = 0 and iUTId in ({ids:array})',
                    'bind' => ['ids' => $getIds]
                ]);
                foreach ($getObjArr as $getObj) {
                    $getObj->bDone = 1;
                    $getObj->iReceiveStatus = 3;
                    if (!$getObj->save()) {
                        throw new XhException('领用归还失败');
                    }
                }
            }
            //合并入库
            $mergeArr = [];
            foreach ($data as $row) {
                $mergeArr[$row['iProdId']][] = $row;
            }
            foreach ($mergeArr as $index => $row) {
                $teachers = implode(',', array_column($row, 'sUserName'));
                Ims::prodIn(['iProdId' => $index, 'iInNum' => count($row), 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 3, 'iSchoolId' => $row[0]['iSchoolId']], [], '教师机退还入库，教师:' . $teachers, $userId);
            }
        } else if ($source == 4) {
            $codes = array_values(array_filter(array_column($data, 'sDevNumber')));
            if ($codes) {
                $getObjArr = XhsysUsertablet::find([
                    'conditions' => 'bDelete = 0 and sDevNumber in ({codes:array})',
                    'bind' => ['codes' => $codes]
                ]);
                foreach ($getObjArr as $getObj) {
                    $getObj->bDone = 1;
                    $getObj->iReceiveStatus = 3;
                    if (!$getObj->save()) {
                        throw new XhException('演示机归还失败');
                    }
                    $bindObj = XhsysAccountdevicelocked::find([
                        'conditions' => 'bDelete = 0 and sDeviceNumber = :sDeviceNumber:',
                        'bind' => ['sDeviceNumber' => $getObj->sDevNumber]
                    ]);
                    if ($bindObj) { //如果有绑定记录 直接解绑
                        if (!$bindObj->delete()) {
                            throw new XhException('解绑失败');
                        }
                    }
                }
            }
            //合并入库
            $mergeArr = [];
            foreach ($data as $row) {
                if (!$row['iProdId']) {
                    throw new XhException('设备类型未知');
                }
                $mergeArr[$row['iProdId']][] = $row;
            }
            foreach ($mergeArr as $index => $row) {
                Ims::prodIn(['iProdId' => $index, 'iInNum' => count($row), 'iInType' => 2, 'iInTypeId' => $iRTId, 'iDevType' => 6, 'iSchoolId' => $row[0]['iSchoolId']], [], '演示机退还入库，领用人:' . $row[0]['sReceiverName'], $userId);
            }
        } else {
            throw new XhException('未知来源');
        }
        return true;
    }

    /**
     * 获取批量归还扫码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181026
     */
    public function getRetTabBatchQRAction()
    {
        $iRTIdArr = $this->request->getPost('iRTIdArr');
        if (!$iRTIdArr) {
            return $this->sendErrorResponse(400, '缺少归还单号数组');
        }
        if (!is_array($iRTIdArr)) {
            return $this->sendErrorResponse(400, '传入的参数并非数组格式');
        }
        return $this->sendJsonResponse([
            'msg' => Tool::getQRBase64Uri(Tool::buildUrl('device/batchScanReturnQR',[
                'userId' => Main::getLoginUserInfo('userId'),
                'iRTIdArr' => implode(',',$iRTIdArr)
            ]))
        ]);
    }

    /**
     * 批量归还
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by dale  20181026
     */
    public function batchScanReturnQRAction()
    {
        try {
            $userId = $this->request->getQuery('userId');
            $iRTIdArr = $this->request->getQuery('iRTIdArr');
            $iRTIdArr = explode(',', $iRTIdArr);
            if (!$iRTIdArr || !$userId){
                return $this->sendViewError('缺少参数');
            }
            $objArr = XHImsReturnTab::find([
                'conditions' => 'bDelete = 0 and iRTId in ({ids:array})',
                'bind'       => ['ids' => $iRTIdArr]
            ]);
            if (!$objArr->toArray()) {
                return $this->sendViewError('未搜索到对应条件的归还记录');
            }
            foreach ($objArr as $obj) {
                if ($obj->iCreateUserId !=  Main::getLoginUserInfo('userId')) {
                    return $this->sendViewError( '存在单号不属于你');
                }
                if ($obj->iState == 3) {
                    return $this->sendViewError( '存在单号已经领用请不要重复操作');
                }
            }
            $this->db->begin();
            foreach ($objArr as $obj) {
                $obj->iState = 3;
                if (!$obj->save()) {
                    throw new XhException('单号状态修改失败');
                }
                $data = $obj->mData;
                if(!is_array($data)) { //如果没有转化
                    $data = $data ? unserialize($data) : [];
                }
                Main::runUserName($data, ['iUserId' => 'sUserName'], false);
                Ims::runProdIdByName($data, ['sDevType' => 'iProdId']);
                $this->retTablet($data, $userId, $obj->iSource, $obj->iRTId);
            }
            $this->db->commit();
            return $this->sendViewSuccess('批量归还成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }




    /**
     * 删除设备归还
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180730
     */
    public function delTabReturnAction(){
        try {
            $this->db->begin();
            $id = $this->request->getPost('id', 'string');
            $obj = XHImsReturnTab::findFirst($id);
            //自己 + 管理员 + 仓管
            if (!User::isAdmin() && !( Power::exist('Device_ReturnTab_Del') && $obj->iCreateUserId == Main::getLoginUserInfo('userId')) && !Power::exist('Device_ReturnTab_Confirm') ) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            if (!$obj->delete()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '删除失败');
            }
            $inArr = XHImsProduceIn::find([
                'conditions' => 'bDelete = 0 and iInType = 2 and iInTypeId = :iInTypeId:',
                'bind'       => ['iInTypeId' => $obj->iRTId]
            ]);
            if (count($inArr->toArray()) > 0) {
                foreach ($inArr as $in) {
                    $in->bDelete = 1;
                    if (!$in->save()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(400, '删除失败');
                    }
                }
                Ims::uploadData();
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 设备维修统计页
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20180621
     */
    public function getRepairStatAction(){
        $type = $this->request->get('type');
        if (!$type || !in_array($type, ['1', '2'])){
            return $this->sendViewError('统计类型参数错误');
        }
        $this->view->pick('device/repairStat');
        Assets::easyUI('js/device/repairStat.js');
        $data = $this->getRepairStatData($type);
        return $this->view->setVars([
            'data' => $data
        ]);
    }

    /**
     * 获取设备维修统计数据，type=1按状态2按维修项目
     *
     * @param $type
     *
     * @return array
     * @throws XhException
     *
     * create by qgz 20180621
     */
    public function getRepairStatData($type){
        $data = [];
        if ($type == 1){//按状态
            $enum = $this->registerEnum['progress'];
            foreach ($enum as $key => $value){
                $allStatusArr[$key] = ['iStatus' => $value, 'statNum' => 0];
            }
            $parameters = [
                'columns' => ' COUNT(*) as statNum, iStatus ',
                'conditions' => ' bDelete = 0 ',
                'group' => 'iStatus',
                'order' => 'iStatus ASC',
            ];
	        $userId = User::getId();
            $powerIds = School::getPower();
            if ($powerIds !== true) {
	            if (!empty($powerIds)){
		            $parameters['conditions'] .= ' AND ( iSchoolId IN (' . implode(',', $powerIds) . ') or ((iSchoolId is null or iSchoolId = 0) and iCreateUserId = '.$userId.'))';
	            } else {
		            $parameters['conditions'] .= " AND (iSchoolId is null or iSchoolId = 0) and iCreateUserId = $userId";//没有学校id的，创建者可查看
	            }
            }

            $repairData = XhsysDevicerepair::find($parameters)->toArray();
            foreach ($repairData as $row){
                if (isset($allStatusArr[$row['iStatus']])){
                    $allStatusArr[$row['iStatus']]['statNum'] = $row['statNum'];
                }
            }
            $data = array_values($allStatusArr) == null ? [] : array_values($allStatusArr);
        } elseif ($type == 2) {//按维修项目
            $enumData = $this->getProjectEnum();
            foreach ($enumData as $value){
                $projectRowsArr[$value] = ['iStatus' => $value, 'statNum' => 0];
            }
            $parameters = [
                'columns' => 'sRepairProjectName',
                'conditions' => " bDelete = 0 AND sRepairProjectName IS NOT NULL AND sRepairProjectName != '' "
            ];
	        $userId = User::getId();
            $powerIds = School::getPower();
            if ($powerIds !== true) {
                if (!empty($powerIds)){
                    $parameters['conditions'] .= ' AND ( iSchoolId IN (' . implode(',', $powerIds) . ') or ((iSchoolId is null or iSchoolId = 0) and iCreateUserId = '.$userId.'))';
                } else {
	                $parameters['conditions'] .= " AND (iSchoolId is null or iSchoolId = 0) and iCreateUserId = $userId";//没有学校id的，创建者可查看
                }
            }

            $repairData = XhsysDevicerepair::find($parameters)->toArray();
            foreach ($repairData as $datum){
                foreach ($projectRowsArr as $key => $row){
                    if (strpos($datum['sRepairProjectName'], $row['iStatus']) !== false){
                        $projectRowsArr[$key]['statNum']++;
                    }
                }
            }
            $data = array_values($projectRowsArr) == null ? [] : array_values($projectRowsArr);
        }
        return $data;
    }

	/**
	 * 导出统计列表数据--新方式
	 *
	 * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180827
	 */
    public function exportRepairStatAction(){
	    $type = $this->request->getQuery('type');
	    $this->view->disable();
	    try {
		    $statData = $this->getRepairStatData($type);
		    $title = [
			    'iStatus' => $type == 1 ? '状态' : '维修项目',
			    'statNum' => '数量'
		    ];
		    $data = [];
		    foreach ($statData as $value) {
			    $row = [];
			    foreach ($title as $filed => $name) {
				    $row[$filed] = Tool::getValue($value, $filed);
			    }
			    $data[] = $row;
		    }
		    $fileName  = $type == 1 ? '设备维修-状态统计表' : '设备维修-维修项目统计表';
		    $titleName = $type == 1 ? '状态统计表' : '维修项目统计表';
		    Tool::exportExcelOnline($fileName, $title, $data,'xlsx', ['autoWidth' => true, 'header' => ['title' => $titleName]]);
		    return true;
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500  , $e->getMessage());
	    }
    }
//    /**
//     * 导出统计列表数据
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by qgz 20180621
//     */
//    public function exportRepairStat1Action(){
//        $type = $this->request->getQuery('type');
//        $this->view->disable();
//        try {
//            $data = $this->getRepairStatData($type);
//            require_once APP_PATH . '/common/library/PHPExcel/PHPExcel.php';
//            require_once APP_PATH . '/common/library/PHPExcel/PHPExcel/IOFactory.php';
//
//            $objPHPExcel = new \PHPExcel();
//            $objPHPExcel->setActiveSheetIndex(0);
//            $sheet = $objPHPExcel->getActiveSheet();
//            $titleName = $type == 1 ? '状态统计表' : '维修项目统计表';
//            $sheet->setTitle($titleName);
//
//            //所有单元格居中
//            $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            $objPHPExcel->getDefaultStyle()->getFont()->setSize(12)->setName('宋体');
//
//            //设置头
//            $sheet->getRowDimension(1)->setRowHeight(40);
//            $sheet->mergeCells('A1:C1');
//            $sheet->setCellValue('A1', $type == 1 ? '状态统计表' : '维修项目统计表');
//            $sheet->getStyleByColumnAndRow('A', 1)->getFont()->setSize(18);
//
//            $titleArr = [
//                ['name' => '序号', 'width' => '5'],
//                ['name' => $type == 1 ? '状态' : '维修项目', 'width' => '20'],
//                ['name' => '数量', 'width' => '6']
//            ];
//
//            //设置excel列名
//            $cell = 'A';
//            $bCell = '';
//            $sheet->getRowDimension(1)->setRowHeight(30);
//            foreach ($titleArr as $key => $title) {
//                if ($cell > 'Z') {
//                    if ($bCell == '') {
//                        $bCell = 'A';
//                    } else {
//                        $bCell++;
//                    }
//                    $cell = 'A';
//                }
//                $sheet->setCellValue($bCell . $cell . '2', $title['name']);
//                $sheet->getColumnDimension($bCell . $cell)->setWidth($title['width']);
//                $cell++;
//            }
//
//            //把数据循环写入excel中
//            foreach($data as $key => $row){
//                $key += 3;
//                $sheet->setCellValueExplicit('A' . $key, $key - 2);
//                $sheet->setCellValueExplicit('B' . $key, $row['iStatus']);
//                $sheet->setCellValueExplicit('C' . $key, $row['statNum']);
//                $sheet->getRowDimension($key)->setRowHeight(30);
//            }
//
//            //边框线
//            $sheet->getStyle('A2:C'. (count($data) + 2))->applyFromArray([
//                'borders' => [
//                    'allborders' => [
//                        //'style' => PHPExcel_Style_Border::BORDER_THICK,   //边框是粗的
//                        'style' => \PHPExcel_Style_Border::BORDER_THIN,     //细边框
//                        //'color' => array('argb' => 'FFFF0000'),
//                    ],
//                ]
//            ]);
//
//            //导出代码
//            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//            $fileName  = $type == 1 ? '设备维修-状态统计表.xlsx' : '设备维修-维修项目统计表.xlsx';
//            header('Content-Type: application/vnd.ms-excel');
//            header('Content-Type: application/octet-stream');
//            header('Content-Disposition: attachment; filename="' . $fileName . '"');
//            header('Cache-Control: max-age=0');
//
//            return $objWriter->save('php://output');
//        }
//        catch (\Exception $e) {
//            return $this->sendErrorResponse( 500  , $e->getMessage());
//        }
//    }

	/**
	 * 导出Excel使用新方法
	 *
	 * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180827
	 */
    public function exportRepairDataAction(){
	    $this->view->disable();
	    try {
		    $repairData = $this->getRepairDataAction(true);
		    $title = [
			    'sSchoolName' => '学校',
                'gradeClass' => '班级',
			    'sUserName' => '姓名',
			    'sModel' => '设备型号',
			    'sDeviceNumber' => '设备号',
			    'sImei' => 'IMEI',
			    'sRepairProjectName' => '维修项目',
			    'sRemark' => '故障描述',
                'iCreateUserId' => '创建人'
		    ];
		    $data = [];
		    foreach ($repairData as $value) {
			    $row = [];
			    foreach ($title as $filed => $name) {
				    $row[$filed] = Tool::getValue($value, $filed);
			    }
			    $data[] = $row;
		    }
		    $fileName = '设备维修统计表';
		    Tool::exportExcelOnline($fileName, $title, $data,'xlsx', ['autoWidth' => true, 'header' => ['title' => '设备维修统计表']]);
		    return true;
	    } catch ( \Exception $e ) {
		    return $this->sendErrorResponse( 500  , $e->getMessage());
	    }
    }

    /**
     * 设备类型修改
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181023
     */
    public function modifyChargeModeAction()
    {
        try {
            $ids = $this->request->getPost('ids', 'string');
            $chargeMode = $this->request->getPost('chargeMode', 'int');
            if (!$ids || !$chargeMode) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $objArr = XHImsApplyTablet::find([
                'conditions' => 'bDelete = 0 and iRTId in ({ids:array}) ',
                'bind'       => ['ids' => $ids]
            ]);
            if (!$objArr->toArray()) {
                return $this->sendErrorResponse(400, '未找到设备申领记录');
            }
            $this->db->begin();
            foreach ($objArr as $obj) {
                if (!in_array($obj->iType, [1, 2])) {
                    continue;
                }
                $obj->iChargeMode = $chargeMode;
                if (!$obj->save(null, null, false)) {
                    throw new XhException('保存失败');
                }
                if ($obj->iBPPId) {
                    $outArr = XHImsProduceOut::find([
                        'conditions' => 'bDelete = 0 and iDevType = 2 and iOutType = 2 and iOutTypeId = :iOutTypeId:',
                        'bind'       => ['iOutTypeId' => $obj->iRTId ]
                    ]);
                    if ($outArr->toArray()) {
                        foreach ($outArr as $out) {
                            $out->iChargeMode = $chargeMode;
                            if (!$out->save(null, null, false)) {
                                throw new XhException('出库修改失败');
                            }
                        }
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('更新成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 更新流程计划的租用状态的
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20181022
     */
    public function replacePlanDevSourceAction()
    {
        $tabletArr = XHImsApplyTablet::find([
            'conditions' => 'bDelete= 0 and iState = 3 and iType = 1',
        ])->toArray();
        foreach ($tabletArr as $tablet) {
            if ($tablet['sClasses'] && $tablet['iChargeMode']) {
                $classes = explode(',', $tablet['sClasses']);
                $sql = " update XHSys_User set iDevSource = {$tablet['iChargeMode']} where  iUserType = 1
                                and  sAdClsName in ('" . implode("','", $classes) . "') and
                                iSchoolId = {$tablet['iSchoolId']} and iDevSource = 0  ";
                $res = $this->db->execute($sql);
                if (!$res) {
                    $this->createCommitLog('学生购置方式更新失败', ['sql' => $sql,'classes' => $tablet['sClasses']]);
                }
            }
        }
    }

    /**
     * 更新学生机申领领用 学生机
     *
     * @return bool
     *
     * create by dale  20181022
     */
    public function replaceStuDevSourceAction() {
        $tabletArr = XHImsApplyTablet::find([
            'conditions' => 'bDelete= 0 and iState = 3 and iType = 2',
        ])->toArray();
        foreach ($tabletArr as $tablet) {
            if ($tablet['sStudents']) {
                $studentIdArr = explode(',', $tablet['sStudents']);
                if ($studentIdArr) {
                    if ($tablet['iChargeMode']) {
                        $sql = "update  XHSys_User set iDevSource = {$tablet['iChargeMode']} where  iUserType = 1
                            and  iUserId in (" . implode(',', $studentIdArr) . ") ";
                        $res = $this->db->execute($sql);
                        if (!$res) {
                            $this->createCommitLog('学生购置方式更新失败',['sql' => $sql,'studentIdArr' => $studentIdArr]);
                        }
                        return true;
                    }
                }
            }
        }

    }

    /**
     * 盒子资料列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181101
     */
    public function boxInfoAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/device/deviceBoxInfo.js');
        if (!Power::exist('deviceBoxInfo')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        $boxStatus = ['' => '-状态-'] + $this->boxStatus;
        $boxType = ['' => '-盒子类型-'] + $this->boxType;
        $schoolType = ['' => '-学校类型-'] + $this->schoolType;
        $schoolStatus = ['' => '-学校状态-'] + [1 => '无Id', 2 => '有Id'];
        $macStatus = ['' => '-Mac-'] + [1 => '无', 2 => '有'];
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'box_info_status', 'style' => 'width: 70px;', 'data' => $boxStatus];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'box_info_boxType', 'style' => 'width: 90px;', 'data' => $boxType];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'box_info_schoolType', 'style' => 'width: 90px;', 'data' => $schoolType];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'box_info_schoolStatus', 'style' => 'width: 90px;', 'data' => $schoolStatus];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'box_info_macStatus', 'style' => 'width: 70px;', 'data' => $macStatus];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        $listSearchArr[] = ['type'=>'button', 'id'=>'bt_list_search', 'text' => '查找', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        if (Power::exist('deviceBoxInfo_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '添加', 'plain' => 'true', 'icon' => 'fa-plus'];
        }
        if (Power::exist('deviceBoxInfo_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        $power['check'] = true;
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHSys_DeviceBoxInfo', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'power' => $power
        ]);
    }

    /**
     * 获取盒子数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by qgz 20181107
     */
    public function getBoxInfoDataAction()
    {
        $status = $this->request->getPost('status');
        $search = $this->request->getPost('search');
        $boxType = $this->request->getPost('boxType');
        $schoolType = $this->request->getPost('schoolType');
        $schoolStatus = $this->request->getPost('schoolStatus');
        $macStatus = $this->request->getPost('macStatus');
        $sort = $this->request->getPost('sort');
        $order = $this->request->getPost('order');
        $conditions = ' A.bDelete = 0 ';
        if ($status !== '' && $status !== null) {
            $conditions .= " AND A.iStatus = {$status} ";
        }
        if ($boxType) {
            $conditions .= " AND A.iBoxType = {$boxType} ";
        }
        if ($schoolType !== '' && $schoolType !== null) {
            $conditions .= " AND B.iType = {$schoolType} ";
        }
        if ($schoolStatus) {
            if ($schoolStatus == 1) {
                $conditions .= " AND (B.iSchoolId IS null OR B.iSchoolId = '') ";
            } elseif ($schoolStatus == 2) {
                $conditions .= " AND B.iSchoolId IS NOT null AND B.iSchoolId != '' ";
            }
        }
        if ($macStatus) {
            if ($macStatus == 1) {//没有Mac地址
                $conditions .= " AND (A.sMac IS null OR A.sMac = '') ";
            } elseif ($macStatus == 2) {//有Mac地址
                $conditions .= " AND A.sMac IS NOT null AND A.sMac != '' ";
            }
        }
        if (isset($search['vague']) && $search['vague']) {//搜索
            $searchArr = ['B.sSchoolName', 'B.sProvinceName', 'B.sCityName', 'B.sCountyName', 'B.sDetailedAddress',
                'B.iSchoolId', 'sRoomInfo', 'iBoxId', 'iAutossh', 'iNgrok', 'sIp', 'sMac', 'sConfig', 'C.sProdName'];
            $searchSql = [];
            foreach ($searchArr as $item) {
                $searchSql[] = " $item like '%{$search['vague']}%' ";
            }
            $searchSql = implode(' OR ', $searchSql);
            $conditions .= " AND ($searchSql)";
        }
        if ($sort && $order) {
            $conditions .= " ORDER BY A.{$sort} {$order}";
        }
        $sql = [
            'columns' => ' A.*, B.iSchoolId, B.sSchoolName, B.iType, B.sProvinceName as sProvince, B.sCityName as sCity,
            B.sCountyName as sDistrict, B.sDetailedAddress as sLocation, C.sProdName ',
            'query' => "SELECT :columns: FROM `XHDevice_BoxInfo` A LEFT JOIN `XHCust_Info` B ON A.iCUId = B.iCUId LEFT JOIN `XHIms_Produce` C ON A.sModel = C.iProdId  WHERE {$conditions}"
        ];
        $data = Main::runSqlPage($sql, ['iStatus' => $this->boxStatus, 'iBoxType' => $this->boxType, 'iType' => $this->schoolType]);
        $this->addOtherBoxInfo($data['rows']);
        return $this->sendJsonResponse($data);
    }

    /**
     * 脚本修复状态（一次）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181203
     */
    public function runBoxTypeAction()
    {
        $data = XhdeviceBoxInfo::find([
            'conditions' => ' bDelete = 0'
        ]);
        if (!$data) {
            echo '没有需要更新的数据';
        }
        try {
            foreach ($data as $value) {
                echo '开始处理数据id:' . $value->iId . ';开始状态值：' . $value->iStatus . '；';
                if ($value->sMac) {
                    $value->iStatus = $this->getBoxStatusByMac($value->sMac);
                } else {
                    $value->iStatus = 2;//断开
                }
                if (!$value->save(null, null, true)) {
                    echo '保存出错；' . '<br>';
                } else {
                    echo '结束处理:' . '结束状态值：' . $value->iStatus . '<br>';
                }
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 添加其他信息
     *
     * @param $data
     *
     * create by qgz 20181101
     */
    public function addOtherBoxInfo(&$data)
    {
        foreach ($data as &$datum) {
            $color = '';
            switch ($datum['iStatus']) {
                case '无' :
                    $color = 'background-color: yellow';
                    break;
                case '在线' :
                    $color = 'background-color: green; color: white';
                    break;
                case '断开' :
                    $color = 'background-color: red; color: white';
                    break;
                case '不合作' :
                    $color = 'background-color: black; color: white';
                    break;
            }
            $datum['iStatus'] = '<div style="' . $color . '">' . $datum['iStatus'] . '</div>';
            if ($datum['iSchoolId']) {
                $datum['schoolIdInfo'] = $datum['iSchoolId'];
            }
        }
    }

    /**
     * 新增/修改盒子资料页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by qgz 20181102
     */
    public function addBoxInfoAction()
    {
        $id = $this->request->getQuery('id');
        $this->view->pick('device/addBoxInfo');
        Assets::select2();
        Assets::easyUI('js/device/addBoxInfo.js');
        if (!Power::exist('deviceBoxInfo_Add') && !$id) {
            return $this->sendViewError('对不起，您没有权限添加');
        }
        if (!Power::exist('deviceBoxInfo_Edit') && $id) {
            return $this->sendViewError('对不起，您没有权限修改');
        }
        $schoolList = $modelArr = $userId = ['' => ''];
//        try {
//            $areaObj = new Area();
//            $provAllData = $areaObj->getAllProvinces(true);//省份
//            foreach ($provAllData as $value) {
//                $provArr[$value] = $value;
//            }
//        } catch (\Exception $e) {
//            $this->createCommitLog($e->getMessage());
//        }
//        $schoolList = $schoolList + School::getSchools();//学校
        try {
            $modelArr = $modelArr + Ims::getProdsByTypeName('盒子');
        } catch (\Exception $e) {
            $modelArr = [];
        }
        $allSchool = XhcustInfo::find([
            'conditions' => 'bDelete = 0'
        ])->toArray();
        if ($allSchool) {
            $schoolList = $schoolList + array_column($allSchool, 'sSchoolName', 'iCUId');//学校
        }
//        $staff = XhhrmStaff::find([
//            'columns' => 'iUserId,sStaffName',
//            'conditions' => 'bDelete= 0 and iStaffStatus = 1 and iUserId is not null'
//        ])->toArray();
//        $userId = $userId + array_column($staff , 'sStaffName' , 'iUserId');
        return $this->view->setVars([
//            'provArr' => $provArr,
            'status' => $this->boxStatus,
            'boxType' => $this->boxType,
            'schoolList' => $schoolList, //客户列表
            'modelList' => $modelArr, //型号列表
//            'userList' => $userId //领用人列表
        ]);
    }

    /**
     * 根据客户id获取客户地址信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by qgz 20181107
     */
    public function getLocationByIdAction()
    {
        $customerId = $this->request->getPost('customerId');
        $return = ['locationInfo' => ''];
        if (!$customerId) {
            return $this->sendJsonResponse($return);
        }
        $schoolInfo = XhcustInfo::findFirst([
            'conditions' => 'bDelete = 0 and iCUId = :iCUId:',
            'bind' => ['iCUId' => $customerId]
        ]);
        if (!$schoolInfo) {
            return $this->sendJsonResponse($return);
        }
        if ($schoolInfo->sProvinceName) {
            $return['locationInfo'] .= $schoolInfo->sProvinceName . '-';
        }
        if ($schoolInfo->sCityName) {
            $return['locationInfo'] .= $schoolInfo->sCityName . '-';
        }
        if ($schoolInfo->sCountyName) {
            $return['locationInfo'] .= $schoolInfo->sCountyName . '-';
        }
        if ($schoolInfo->sDetailedAddress) {
            $return['locationInfo'] .= $schoolInfo->sDetailedAddress;
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 根据省获取市
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181102
     */
    public function getCityByProvAction()
    {
        $provId = $this->request->getPost('provId');
        $return[] = ['id' => '', 'text' => ''];
        if (empty($provId)){
            return $this->sendJsonResponse($return);
        } elseif ($provId == '全国') {
            return $this->sendJsonResponse(['id' => '全国', 'text' => '全国']);
        }
        $id = '';
        try {
            $areaObj = new Area();
            $provArr = $areaObj->getAllProvinces(true);
            foreach ($provArr as $key => $item){
                if($item == $provId){
                    $id = $key;
                    break;
                }
            }
            $areaObj = new Area((int)$id);
            $allCity = $areaObj->getCity();
            foreach ($allCity as $value){
                $return[] = ['id' => $value, 'text' => $value];
            }
            return $this->sendJsonResponse($return);
        } catch ( \Exception $e ) {
            return $this->sendErrorResponse( 400, '学校还没有设置所属的区域，请先设置省市区信息' );
        }
    }

    /**
     * 根据获取市获取区县
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181102
     */
    public function getDistrictByCityAction()
    {
        $provId = $this->request->getPost('provId');
        $cityId = $this->request->getPost('cityId');
        $return[] = ['id' => '', 'text' => ''];
        if (empty($provId) || empty($cityId)){
            return $this->sendJsonResponse($return);
        }
        $isCQ = false;
        if ($provId == '重庆市') {//重庆市的话加上丰都县，姚超让加的
            $isCQ = true;
        }
        try {
            $id = $getCityId = '';
            $areaObj = new Area();
            $provArr = $areaObj->getAllProvinces(true);
            foreach ($provArr as $key => $item){
                if($item == $provId){
                    $id = $key;
                    break;
                }
            }
            $areaObj = new Area((int)$id);
            $allCity = $areaObj->getCity();
            foreach ($allCity as $item => $value){
                if($value == $cityId){
                    $getCityId = $item;
                    break;
                }
            }
            $areaObj = new Area((int)$getCityId);
            $allDistrict = $areaObj->getDistrict();
            if ($isCQ) {
                $allDistrict[500230] = '丰都县';
            }
            foreach ($allDistrict as $value){
                $return[] = ['id' => $value, 'text' => $value];
            }
            return $this->sendJsonResponse($return);
        } catch ( \Exception $e ) {
            return $this->sendErrorResponse( 400, '学校还没有设置所属的区域，请先设置省市区信息' );
        }
    }

    /**
     * 根据省、市份获取地图数值
     *
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * //data:学校=>学校具体地址,local:展示地图当前中心点,level：地图缩放等级，数值越大越范围越小
     * create by qgz 20181112
     */
    public function getMapDataByProvAction()
    {
        $provId = $this->request->getPost('provId');
        $cityId = $this->request->getPost('cityId');
        if (!$provId) {
            return $this->sendErrorResponse(400, '缺少省份id');
        }
        $return = ['data' => [], 'local' => '', 'level' => 5];
        $conditions = [
            'columns' => ' iCUId, sSchoolName, sProvinceName, sCityName, sCountyName, sDetailedAddress ',
            'conditions' => " bDelete = 0 and iCUId in (SELECT a.iCUId FROM Admin\\Models\\device\\XhdeviceBoxInfo a ".
                            " WHERE a.bDelete = 0 ) ",
//            'conditions' => " bDelete = 0 ",
        ];
        if ($provId == '全国') {
            $return['local'] = '浙江省';
        } else {
            $return['local'] = $cityId ? $provId . '-' . $cityId : $provId;
            $return['level'] = $cityId ? 13 : 9;
            $conditions['conditions'] .= " and sProvinceName = '{$provId}' ";
            if ($cityId) {
                $conditions['conditions'] .= " and sCityName = '{$cityId}' ";
            }
        }
        $data = XhcustInfo::find($conditions)->toArray();
        if ($data) {
            foreach ($data as $value) {
                $return['data'][$value['sSchoolName']] = $value['sProvinceName'].'-'.$value['sCityName'].'-'.$value['sCountyName'].'-'. $value['sDetailedAddress'];
            }
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 根据盒子id获取盒子数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181105
     */
    public function getBoxInfoByIdAction()
    {
        $id = $this->request->getPost('id');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少参数id');
        }
        $data = XhdeviceBoxInfo::findFirst([
            'conditions' => ' bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $id]
        ]);
        if (!$data) {
            return $this->sendErrorResponse(500, '暂无数据');
        }
        $data = $data->toArray();
        return $this->sendJsonResponse($data);
    }

    /**
     * 新建盒子资料信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by qgz 20181102
     */
    public function saveBoxInfoDataAction()
    {
        $postData = $this->request->getPost();
        $postData['iStatus'] = $postData['sMac'] ? $this->getBoxStatusByMac($postData['sMac']) : 2;
        if (isset($postData['iId']) && $postData['iId']) {//修改
            try {
                $boxInfo = XhdeviceBoxInfo::findFirst([
                    'conditions'  => 'iId = :iId:',
                    'bind' => ['iId' => $postData['iId']]
                ]);
                if (!$boxInfo) {
                    return $this->sendErrorResponse(500, '找不到数据');
                }
                unset($postData['iId']);
                if (!$boxInfo->update($postData)) {
                    return $this->sendErrorResponse(500, '保存错误');
                }
            } catch (\Exception $e) {
                return $this->sendErrorResponse(500, $e->getMessage());
            }
        } else {
            $boxInfo = new XhdeviceBoxInfo();
            if (!$boxInfo->create($postData)) {
                return $this->sendErrorResponse(500, '保存错误');
            }
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 根据mac获取盒子的状态，离线或在线
     *
     * @param string $mac
     *
     * @return int
     * @throws XhException
     *
     * create by qgz 20181109
     */
    public function getBoxStatusByMac($mac = '')
    {
        $data = Box::getBoxStatusByMac($mac);//返回是字符串
        return $data == 'not found' ? 2 : 1;//离线或在线
    }

    /**
     * 删除盒子信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181105
     */
    public function delBoxInfoAction()
    {
        $id = $this->request->getPost('id');
        if (!$id) {
            return $this->sendErrorResponse(400, '请选择后操作');
        }
        $data = XhdeviceBoxInfo::find([
            'conditions' => 'bDelete = 0 and iId in ({idArr:array})',
            'bind' => ['idArr' => $id]
        ]);
        if (!$data) {
            return $this->sendErrorResponse(500, '没有数据');
        }
        foreach ($data as $value) {
            $value->bDelete = 1;
            if (!$value->save()) {
                return $this->sendErrorResponse(500, '删除错误');
            }
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 盒子资料统计页面 注：（盒子在线情况统计）只统计有mac的记录数（不是mac数），不去重mac；学校总数统计所有有学校的记录（学校个数），去重学校；型号是所有记录型号统计（空为other）；
     *
     * @return \Phalcon\Mvc\View
     *
     * create by qgz 20181108
     */
    public function countBoxInfoAction()
    {
        $this->view->pick('device/countBoxInfo');
        Assets::xhChart();
        Assets::easyUI('js/device/countBoxInfo.js');
        if (!Power::exist('deviceBoxCount')) {
            return $this->sendViewError('你没有权限查看');
        }
        $count = [
            'totalSchoolNum' => 0, 'fileBox' => 0, 'classBox' => 0, 'otherBox' => 0,
            'fileOnline' => 0, 'fileOffline' => 0, 'classOnline' => 0, 'classOffline' => 0,
            'otherOnline' => 0, 'otherOffline' => 0
            ];
        $schoolArr = [];

        try {
            $allModelArr = Ims::getProdsByTypeName('盒子');
        } catch (\Exception $e) {
            $allModelArr = [];
        }
        $modelArr = $this->handleModelData($allModelArr);
        $allData = XhdeviceBoxInfo::find(['conditions' => 'bDelete = 0 '])->toArray();
        if (!$allData) {
            $modelChart = $this->handleChartData($count, $modelArr);
            return $this->view->setVars([
                'data' => $count,
                'model' => $modelArr,
                'chart_data' => json_encode($modelChart['count']),
                'chart_model' => json_encode($modelChart['model']),
            ]);
        }
        foreach ($allData as $value) {
            if ($value['iCUId']) {
                //统计总学校数
                if (!in_array($value['iCUId'], $schoolArr)) {
                    $schoolArr[] = $value['iCUId'];
                    $count['totalSchoolNum'] ++;
                }
//                //文件盒子学校数
//                if ($value['iBoxType'] == 1 && !in_array($value['iCUId'], $schoolArr['fileBox'])) {
//                    $schoolArr['fileBox'][] = $value['iCUId'];
//                }
//                //课堂盒子学校数
//                if ($value['iBoxType'] == 2 && !in_array($value['iCUId'], $schoolArr['classBox'])) {
//                    $schoolArr['classBox'][] = $value['iCUId'];
//                }
            }
            if ($value['sMac']) {//只统计有Mac地址的
                if ($value['iBoxType'] == 1) {//文件盒子
                    $count['fileBox'] ++;
                    if ($value['iStatus'] == 1) {//在线
                        $count['fileOnline'] ++;
                    } elseif ($value['iStatus'] == 2) {//离线
                        $count['fileOffline'] ++;
                    }
                } elseif ($value['iBoxType'] == 2) {//课堂盒子
                    $count['classBox'] ++;
                    if ($value['iStatus'] == 1) {//在线
                        $count['classOnline'] ++;
                    } elseif ($value['iStatus'] == 2) {//离线
                        $count['classOffline'] ++;
                    }
                } else {//其他盒子
                    $count['otherBox'] ++;
                    if ($value['iStatus'] == 1) {//在线
                        $count['otherOnline'] ++;
                    } elseif ($value['iStatus'] == 2) {//离线
                        $count['otherOffline'] ++;
                    }
                }
            }
            if ($value['sModel'] && isset($allModelArr[$value['sModel']])) {
                $modelArr[$allModelArr[$value['sModel']]]++;
            } else {
                $modelArr['other'] = isset($modelArr['other']) ? $modelArr['other']++ : 1;
            }
        }
        $modelChart = $this->handleChartData($count, $modelArr);
        return $this->view->setVars([
            'data' => $count,
            'model' => $modelArr,
            'chart_data' => json_encode($modelChart['count']),
            'chart_model' => json_encode($modelChart['model']),
        ]);
    }

    /**
     * 盒子地图分布
     *
     * @return \Phalcon\Mvc\View
     *
     * create by qgz 20181112
     */
    public function boxInfoMapAction()
    {
        $this->view->pick('device/boxInfoMap');
        if (!Power::exist('deviceBoxMap')) {
            return $this->sendViewError('你没有权限查看');
        }
        Assets::select2();
        Assets::easyUI('js/device/boxInfoMap.js');
        $data = [];
        $provArr = ['全国' => '全国'];
        try {
            $areaObj = new Area();
            $provAllData = $areaObj->getAllProvinces(true);//省份
            foreach ($provAllData as $value) {
                $provArr[$value] = $value;
            }
        } catch (\Exception $e) {
            $this->createCommitLog($e->getMessage());
        }

        return $this->view->setVars([
            'data' => $data,
            'pro' => $provArr
        ]);
    }

    /**
     * 处理型号类型数据
     *
     * @param array $model
     *
     * @return array
     *
     * create by qgz 20181108
     */
    public function handleModelData($model = [])
    {
        $return = [];
        if (!$model) {
            return $return;
        }
        $model = array_values($model);
        foreach ($model as $value) {
            $return[$value] = 0;
        }
        return $return;
    }

    /**
     * 处理数据成柱状图\屏状体使用数据
     *
     * @param array $count
     * @param array $model
     *
     * @return array
     *
     * create by qgz 20181106
     */
    public function handleChartData($count = [], $model = [])
    {
        $return = ['count' => [], 'model' => []];
        $return['count'] = [
            'all' => [$count['fileBox'], $count['classBox'], $count['otherBox']],
            'offline' => [$count['fileOffline'], $count['classOffline'], $count['otherOffline']],
            'online' => [$count['fileOnline'], $count['classOnline'], $count['otherOnline']],
            'total' => $count['totalSchoolNum']//title学校总数
        ];
        $data = [];
        foreach ($model as $key => $value) {
            $data[] = ['value' => $value,'name' => $key];
        }
        $return['model'] = ['series' => $data, 'legend' => array_keys($model)];
        return $return;
    }

//    /**
//     * 导出设备维修数据表
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by qgz 20180622
//     */
//    public function exportRepairData1Action(){
//        $this->view->disable();
//        try {
//            $data = $this->getRepairDataAction(true);
//            require_once APP_PATH . '/common/library/PHPExcel/PHPExcel.php';
//            require_once APP_PATH . '/common/library/PHPExcel/PHPExcel/IOFactory.php';
//
//            $objPHPExcel = new \PHPExcel();
//            $objPHPExcel->setActiveSheetIndex(0);
//            $sheet = $objPHPExcel->getActiveSheet();
//            $titleName = '设备维修统计表';
//            $sheet->setTitle($titleName);
//
//            //所有单元格居中
//            $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            $objPHPExcel->getDefaultStyle()->getFont()->setSize(12)->setName('宋体');
//
//            //设置头
//            $sheet->getRowDimension(1)->setRowHeight(40);
//            $sheet->mergeCells('A1:H1');
//            $sheet->setCellValue('A1', '设备维修统计表');
//            $sheet->getStyleByColumnAndRow('A', 1)->getFont()->setSize(18);
//
//            $titleArr = [
//                ['name' => '序号', 'width' => '5'],
//                ['name' => '学校', 'width' => '20'],
//                ['name' => '姓名', 'width' => '10'],
//                ['name' => '设备型号', 'width' => '10'],
//                ['name' => '设备号', 'width' => '20'],
//                ['name' => 'IMEI', 'width' => '20'],
//                ['name' => '维修项目', 'width' => '20'],
//                ['name' => '故障描述', 'width' => '60']
//            ];
//
//            //设置excel列名
//            $cell = 'A';
//            $bCell = '';
//            $sheet->getRowDimension(2)->setRowHeight(30);
//            foreach ($titleArr as $key => $title) {
//                if ($cell > 'Z') {
//                    if ($bCell == '') {
//                        $bCell = 'A';
//                    } else {
//                        $bCell++;
//                    }
//                    $cell = 'A';
//                }
//                $sheet->setCellValue($bCell . $cell . '2', $title['name']);
//                $sheet->getColumnDimension($bCell . $cell)->setWidth($title['width']);
//                $cell++;
//            }
//
//            //把数据循环写入excel中
//            foreach($data as $key => $row){
//                $key += 3;
//                $sheet->setCellValueExplicit('A' . $key, $key - 2);
//                $sheet->setCellValueExplicit('B' . $key, isset($row['sSchoolName']) ? $row['sSchoolName'] : '');
//                $sheet->setCellValueExplicit('C' . $key, $row['sUserName']);
//                $sheet->setCellValueExplicit('D' . $key, $row['sModel']);
//                $sheet->setCellValueExplicit('E' . $key, $row['sDeviceNumber']);
//                $sheet->setCellValueExplicit('F' . $key, $row['sImei']);
//                $sheet->setCellValueExplicit('G' . $key, $row['sRepairProjectName']);
//                $sheet->setCellValueExplicit('H' . $key, $row['sRemark']);
//                $sheet->getRowDimension($key)->setRowHeight(30);
//            }
//
//            //边框线
//            $sheet->getStyle('A2:H'. (count($data) + 2))->applyFromArray([
//                'borders' => [
//                    'allborders' => [
//                        //'style' => PHPExcel_Style_Border::BORDER_THICK,   //边框是粗的
//                        'style' => \PHPExcel_Style_Border::BORDER_THIN,     //细边框
//                        //'color' => array('argb' => 'FFFF0000'),
//                    ],
//                ]
//            ]);
//
//            //导出代码
//            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//            $fileName  = '设备维修统计表.xlsx';
//            header('Content-Type: application/vnd.ms-excel');
//            header('Content-Type: application/octet-stream');
//            header('Content-Disposition: attachment; filename="' . $fileName . '"');
//            header('Cache-Control: max-age=0');
//
//            return $objWriter->save('php://output');
//        }
//        catch (\Exception $e) {
//            return $this->sendErrorResponse( 500  , $e->getMessage());
//        }
//    }

    /**
     * 脚本-检测状态是否延时
     *
     *
     * create by qgz 20180914
     */
//    public function runRepairDelayDataAction()
//    {
//        $allDelayData = XhsysDevicerepairDelay::find(['conditions' => 'bDelete = 0']);
//        if (!$allDelayData) {
//            echo 'No data need check.';die;
//        }
//        $delayNum = $applyNum = 0;
//        foreach ($allDelayData as $delayData){
//            if ($delayData->iFinishStatus == 0) {//只检测没完成的
//                if ($delayData->tEndDate) {
//                    if (date('Y-m-d') > $delayData->tEndDate) {//如果延期
//                        $delayData->iDelayStatus = 1;
//                        if (!$delayData->save()) {
//                            echo 'modify iDelayStatus error, delay id:' . $delayData->iId . '</br>';
//                        }
//                        $delayNum++;
//                        $repairApplyData = XhsysDevicerepair::findFirst([
//                            'conditions' => 'bDelete = 0 and iId = :iId:',
//                            'bind' => ['iId' => $delayData->iRepairApplyId]
//                        ]);
//                        $delayRepairStatus = $this->delayRepairStatus[$delayData->iProgressStatus];
//                        if (in_array($repairApplyData->iStatus, $delayRepairStatus)) {//申请表需要记录当前状态是否延时
//                            $repairApplyData->iDelayStatus = $delayData->iProgressStatus;
//                            if (!$repairApplyData->save()) {
//                                echo 'delay id:' . $delayData->iId . ' and repair id :' .
//                                     $repairApplyData->iId . 'have error.' . '</br>';
//                            }
//                            $applyNum++;
//                        }
//                    }
//                }
//            }
//        }
//        echo 'modify delay data num:' . $delayNum . '</br> modify apply data num:' . $applyNum;
//    }


    /**
     * 执行归还列表生成schoolId脚本
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181206
     */
    public function runReTableSchoolIdAction()
    {
        try {
            $reObjArr = XHImsReturnTab::find([
                'conditions' => 'bDelete = 0'
            ]);
            if ($reObjArr->toArray()) {
                foreach ($reObjArr as $reObj) {
//                    if ($reObj->iSchoolId) {
//                        continue;
//                    }
                    $mData = $reObj->mData;
                    if (!is_array($mData)) {
                        $mData = $reObj->mData ? unserialize($reObj->mData) : [];
                    }
                    $schoolId = 0;
                    foreach ($mData as $row) {
                        $schoolId = Tool::getValue($row, 'iSchoolId', 0);
                    }
                    if ($reObj->iSchoolId != $schoolId) {
                        $reObj->iSchoolId = $schoolId;
                        if (!$reObj->save(null,null, false)) {
                            $this->createCommitLog("保存失败,iRTId={$reObj->iRTId},iSchoolId={$schoolId}",
                                "保存失败,iRTId={$reObj->iRTId},iSchoolId={$schoolId}");
                        }
                    }
                }
                return $this->sendSuccessResponse('执行成功');
            } else {
                return $this->sendSuccessResponse('没有记录需要执行');
            }

        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 脚本，插入用户设备号，教师机
     *
     *
     * create by qgz 20181220
     */
    public function setUserDeviceInfoAction()
    {
        $schoolId = 4110;
//        $tchInfo = [
//            ['devNumber' => 'R22H7008X9Y', 'account' => 'xczxqjy'],
//            ['devNumber' => 'R22JC0062MN', 'account' => 'xczxcy1'],
//            ['devNumber' => 'R22H7004BHX', 'account' => 'xczxwcy'],
//            ['devNumber' => 'R22H70000AX', 'account' => 'xczxczz'],
//            ['devNumber' => 'R22H7004NMP', 'account' => 'xczxxdx'],
//            ['devNumber' => 'R22H7008TGF', 'account' => 'xczxzbb'],
//            ['devNumber' => 'R22H7004PNV', 'account' => 'xczxrcl'],
//            ['devNumber' => 'R22H700012K', 'account' => 'xczxrhh'],
//            ['devNumber' => 'R22H70045SK', 'account' => 'xczxsjm'],
//            ['devNumber' => 'R22H7008BRF', 'account' => 'xczxzyj'],
//            ['devNumber' => 'R22H7004A4P', 'account' => 'xczxcmz'],
//            ['devNumber' => 'R22HB00K7QE', 'account' => 'xczxjcj'],
//            ['devNumber' => 'R22H70000DB', 'account' => 'xczxtmy'],
//            ['devNumber' => 'R22H70093YA', 'account' => 'xczxxlq1'],
//            ['devNumber' => 'R22H700402Y', 'account' => 'xczxmyj'],
//            ['devNumber' => 'R22H70093VR', 'account' => 'xczxwcx'],
//            ['devNumber' => 'R22H7004LHJ', 'account' => 'xczxhm'],
//            ['devNumber' => 'R22H70002CF', 'account' => 'xczxqsl'],
//            ['devNumber' => 'R22H70007WT', 'account' => 'xczxzy'],
//            ['devNumber' => 'R22H7004NVM', 'account' => 'xczxlh'],
//            ['devNumber' => 'R22H70042PD', 'account' => 'xczxxdq'],
//            ['devNumber' => 'R22H7004GER', 'account' => 'xczxlx'],
//            ['devNumber' => 'R22H70095YT', 'account' => 'xczxchb'],
//            ['devNumber' => 'R22H70043EW', 'account' => 'xczxcmf'],
//            ['devNumber' => 'R22H700461Y', 'account' => 'xczxcf'],
//            ['devNumber' => 'R22H7003W7F', 'account' => 'xczxxxb'],
//            ['devNumber' => 'R22H70049EB', 'account' => 'xczxxlp'],
//            ['devNumber' => 'R22H70093XB', 'account' => 'xczxzly'],
//            ['devNumber' => 'R22H70044DT', 'account' => 'xczxpjp'],
//            ['devNumber' => 'R22H70095RJ', 'account' => 'xczxdjm'],
//            ['devNumber' => 'R22H70095GW', 'account' => 'xczxzyk'],
//            ['devNumber' => 'R22H7004P4K', 'account' => 'xczxllj'],
//            ['devNumber' => 'R22H7004MAR', 'account' => 'xczxlcq'],
//            ['devNumber' => 'R22H7004APP', 'account' => 'xczxjwy'],
//            ['devNumber' => 'R22HB00KKFY', 'account' => 'xczxhwp'],
//            ['devNumber' => 'R22H700013P', 'account' => 'xczxlcq'],
//            ['devNumber' => 'R22H700430V', 'account' => 'xczxjwy'],
//            ['devNumber' => 'R22H7000AMX', 'account' => 'xczxhwp'],
//        ];
        $tchInfo = [
            ['devNumber' => 'R22H700438F', 'account' => ''],
            ['devNumber' => 'R22H70002MN', 'account' => ''],
            ['devNumber' => 'R22H7003W8M', 'account' => ''],
            ['devNumber' => 'R22H700489R', 'account' => ''],
        ];

        foreach ($tchInfo as $tch) {
            if ($tch['account']) {
                $userInfo = XhsysUser::findFirst([
                    'columns' => 'iUserId, sUserName, sSelfPhone',
                    'conditions' => 'bDelete = 0 and sLogonName = :sLogonName:',
                    'bind' => ['sLogonName' => $tch['account']]
                ]);
                if (!$userInfo) {
                    $tch['tchName'] = $tch['tchPhone'] = '';
                } else {
                    $tch['tchName'] = $userInfo->sUserName;
                    $tch['tchPhone'] = $userInfo->sSelfPhone;
                }
            } else {
                $tch['tchName'] = $tch['tchPhone'] = '';
            }

            $tchDev = new \Admin\Models\device\XhsysUsertablet();
            $tchDev->sReceiverName = $tch['tchName'];
            $tchDev->sReceiverAccount = $tch['account'];
            $tchDev->sReceiverPhone = $tch['tchPhone'];
            $tchDev->iReceivePurpose = 3;
            $tchDev->tReceiveTime = date('Y-m-d H:i:s');
            $tchDev->sDevNumber = $tch['devNumber'];
            $tchDev->iSchoolId = $schoolId;
            $tchDev->bDone = 0;//使用状态，使用中
            $tchDev->iReceiveStatus = 2;//领用状态，已领用
            $tchDev->iSource = 1;//来源，手动
            $tchDev->iBuyType = 2;//采购类型，校购
            if ($tchDev->save()) {
                echo 'id：' . $tchDev->iUTId . '；info:' . json_encode($tch, JSON_UNESCAPED_UNICODE);
                echo '  插入成功<br />';
            } else {
                echo '  插入失败<br />';
            }
        }
    }

    /**
     * 用户详情--设备信息--设备维修详情 //同设备维修模块一模一样，只是功能比那里少
     *
     * @return View|string
     *
     * create by qgz 20190108
     */
    public function repairDeviceInfoAction()
    {
//        if (!UserPower::checkUserPower('Device_Repair')) {
//            return $this->sendViewError('对不起，您没有查看此页面的权限');
//        }
        $userId = $this->request->getQuery('userId', 'int');
        if (!$userId) {
            return $this->sendViewError('缺少用户id参数');
        }
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/device/repairDeviceInfo.js');
        $listButtonArr = [];
        $listButtonArr[] = ['id' => 'bt_list_commit', 'text' => '沟通记录', 'plain' => 'true', 'icon' => 'fa-commenting-o'];
        $listButtonArr[] = ['id' => 'bt_list_history', 'text' => '流程记录', 'plain' => 'true', 'icon' => 'fa-eye'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHSys_RepairApply', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ]);
    }

    /**
     * 用户详情--设备信息--获取设备维修数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190108
     */
    public function getRepairDeviceInfoAction()
    {
        $userId = $this->request->getPost('userId', 'int');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id参数');
        }
        try {
            $parameters = [
                'conditions' => ' bDelete = 0 AND iUserId = :iUserId: ',
                'bind' => ['iUserId' => $userId],
                'order' => 'tCreateDate DESC',
            ];

            //获取和该用户有关的设备维修数据
            $deviceData = Device::getRepairDevByUserId($userId);
            $devArr = [];
            if ($deviceData) {
                foreach ($deviceData as $datum) {
                    if (!in_array($datum['sDeviceNumber'], $devArr)) {
                        $devArr[] = $datum['sDeviceNumber'];
                    }
                    if (!in_array($datum['sNewDeviceNumber'], $devArr)) {
                        $devArr[] = $datum['sNewDeviceNumber'];
                    }
                }
            }
            if ($devArr) {
                $parameters['conditions'] .= ' AND (sDeviceNumber IN ({sDeviceNumber:array}) OR sNewDeviceNumber IN ({sNewDeviceNumber:array}))';
                $parameters['bind']['sDeviceNumber'] = $devArr;
                $parameters['bind']['sNewDeviceNumber'] = $devArr;
            }

            $enumArr = $this->registerEnum['progress'];
            Main::runSearchVagueConditions($parameters['conditions']);
            $data = Main::runModelPage('Admin\Models\device\XhsysDevicerepair', $parameters,
                [
                    'iStatus'        => $enumArr,
                    'iDestination'   => $this->registerEnum['destination'],
                    'iCheckResult'   => $this->registerEnum['checkResult'],
                    'iAgreeCharge'   => $this->registerEnum['agreeCharge'],
                    'iRenewal'       => $this->registerEnum['renewal'],
                    'iConfirmCharge' => $this->registerEnum['iConfirmCharge'],
                    'iCreateType'    => $this->registerEnum['iCreateType'],
                    'iPurposeType'   => $this->registerEnum['repairPurposeType']
                ]);
            if ($data['total'] != 0) {
                Main::addUserGradeById($data['rows'], ['iUserId' => 'iGradeCode'], true);
                Main::addUserClassById($data['rows'], ['iUserId' => 'sAdClsName']);
                $data = $this->addProgress($data, $enumArr, 'false');
                //替换用户名为小写
                foreach ($data['rows'] as $index => $row) {
                    $data['rows'][$index]['sLogonName'] = strtolower($row['sLogonName']);
                    if ($row['iUserId']) {
                        $row['iGradeCode']                  = isset($row['iGradeCode']) ? $row['iGradeCode'] : '';
                        $row['sAdClsName']                  = isset($row['sAdClsName']) ? $row['sAdClsName'] : '';
                        $data['rows'][$index]['gradeClass'] = $row['iGradeCode'] . $row['sAdClsName'];
                    }
                }

                //绑定上报设备
                $rows            = array_column($data['rows'], null, 'sLogonName');
                $accounts        = array_values(array_filter(array_keys($rows)));
                $receiverAccount = [];
                if (!empty($accounts)) {
                    $deviceInfo = XhsysUsertablet::find([
                        'columns'    => 'iUTId,sNowReceiverAccount,iReceivePurpose,sDevNumber,sDevType,sMacAddress,tCreateDate',
                        'conditions' => 'bDelete = 0 AND bDone = 0 AND sNowReceiverAccount IN ({accounts:array})',
                        'bind'       => ['accounts' => $accounts]
                    ])->toArray();
                    if (!empty($deviceInfo)) {
                        $receiverAccount = array_column($deviceInfo, null, 'sNowReceiverAccount');
                    }
                }
                //绑定借用
                $rows    = array_column($data['rows'], null, 'iUserId');
                $userIds = array_values(array_filter(array_keys($rows)));
                if (!empty($userIds)) {
                    $borrowInfo = XhsysAccountdevicelocked::find([
                        'columns'    => 'iUserId,iADLId,sDeviceNumber,sIP,sMac,sModel,sImei,tCreateDate',
                        'conditions' => "bDelete = 0 AND iSourceType = 2 AND iUserId IN ({studIds:array})",
                        'bind'       => ['studIds' => $userIds]
                    ])->toArray();
                    $idAccount  = [];
                    if (!empty($borrowInfo)) {
                        $idAccount = array_column($borrowInfo, null, 'iUserId');
                    }
                }
                $parentPhoneInfo = $parentNameInfo = [];
                if (!empty($userIds)) {
                    $parentPhoneInfo = XhsysUser::find([
                        'columns'    => 'iUserId, sUserName, sMotherPhone, sFatherPhone, sOtherPhone',
                        'conditions' => "bDelete = 0 and iUserId IN ({iUserId:array})",
                        'bind'       => ['iUserId' => $userIds]
                    ])->toArray();

                    $parentNameInfo = XhsysUserstud::find([
                        'columns'    => 'iUserId, sMotherName, sFatherName, sOtherName',
                        'conditions' => "bDelete = 0 and iUserId IN ({iUserId:array})",
                        'bind'       => ['iUserId' => $userIds]
                    ])->toArray();
                }

                $parentPhoneInfo = array_column($parentPhoneInfo, null, 'iUserId');
                if (!empty($parentNameInfo)) {
                    $parentNameInfo = array_column($parentNameInfo, null, 'iUserId');
                }
                foreach ($parentPhoneInfo as $key => &$val) {
                    if (isset($parentNameInfo[$key])) {
                        $val['sMotherName'] = $parentNameInfo[$key]['sMotherName'];
                        $val['sFatherName'] = $parentNameInfo[$key]['sFatherName'];
                        $val['sOtherName']  = $parentNameInfo[$key]['sOtherName'];
                    } else {
                        $val['sMotherName'] = $val['sFatherName'] = $val['sOtherName'] = null;
                    }
                }
                unset($parentNameInfo);

                foreach ($data['rows'] as &$value) {
                    $value['iAgreeChargeName'] = $value['iAgreeCharge'];
                    if (isset($receiverAccount[$value['sLogonName']])) {
                        $value['iReceivePurpose'] = $receiverAccount[$value['sLogonName']]['iReceivePurpose'] ? '备用' : '自用';
                    }
                    if (isset($idAccount[$value['iUserId']])) {
                        $value['iReceivePurpose'] = '借用';
                    }

                    if ($value['iCheckResult'] == '无法检修') {
                        $value['iCheckResult']   .= '：' . $value['sUnRepairReason'];
                        $value['iConfirmCharge'] = '';
                    } elseif ($value['iCheckResult'] == '收费') {
                        if ($value['iAgreeCharge'] == '不同意') {
                            $value['iAgreeCharge'] = '(' . $value['iAgreeCharge'] . ')沟通内容/原因：' . $value['sDisagreeReason'];
                        } elseif ($value['iAgreeCharge'] == '同意') {
                            $value['iAgreeCharge'] = '(' . $value['iAgreeCharge'] . ')沟通内容：' . $value['sDisagreeReason'];
                        } else {
                            $value['iAgreeCharge'] = '';
                        }
                    } elseif ($value['iCheckResult'] == '免费') {
                        $value['iAgreeCharge']   = '无需收费';
                        $value['iConfirmCharge'] = '无需确认';
                    } else {
                        $value['iConfirmCharge'] = '';
                    }
                    if ($value['sRepairContent']) {
                        if ($value['iRenewal'] == '是') {
                            $value['iRenewal'] = '（变化信息）';
                            if ($value['sNewDeviceNumber']) {
                                $value['iRenewal'] .= '新设备号：' . $value['sNewDeviceNumber'] . '；';
                                $value['iRenewal'] .= '新Imei：' . $value['sNewImei'] . '；';
                            }
                            if ($value['sNewMessage']) {
                                $value['iRenewal'] .= '其他：' . $value['sNewMessage'];
                            }
                        }
                    } else {
                        $value['iRenewal'] = '';
                    }
                    if ($value['sCheckReport']) {
                        $value['sCheckReport'] = '<div><a reportUrl="' . $value['sCheckReport'] . '" ' . ' class="checkReport">点击查看</a></div>';
                    }
                    if ($value['sDocument']) {
                        $value['sDocument'] = '<div><a documentUrl="' . $value['sDocument'] . '" ' . ' class="document">点击查看</a></div>';
                    }
                    $contact = '';
                    if (isset($parentPhoneInfo[$value['iUserId']])) {
                        if ($parentPhoneInfo[$value['iUserId']]['sMotherName'] && $parentPhoneInfo[$value['iUserId']]['sMotherPhone']) {
                            $contact .= '[妈妈]' . $parentPhoneInfo[$value['iUserId']]['sMotherName'] . '：' . $parentPhoneInfo[$value['iUserId']]['sMotherPhone'] . ';';
                        }
                        if ($parentPhoneInfo[$value['iUserId']]['sFatherName'] && $parentPhoneInfo[$value['iUserId']]['sFatherPhone']) {
                            $contact .= '[爸爸]' . $parentPhoneInfo[$value['iUserId']]['sFatherName'] . '：' . $parentPhoneInfo[$value['iUserId']]['sFatherPhone'] . ';';
                        }
                        if ($parentPhoneInfo[$value['iUserId']]['sOtherName'] && $parentPhoneInfo[$value['iUserId']]['sOtherPhone']) {
                            $contact .= '[监护人]' . $parentPhoneInfo[$value['iUserId']]['sOtherName'] . '：' . $parentPhoneInfo[$value['iUserId']]['sOtherPhone'] . ';';
                        }
                    }
                    $value['contact'] = $contact;
                }
                Main::runUserNameById($data['rows'], 'iCreateUserId', true);
                Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
                unset($value);
            }
            return $this->sendJsonResponse($data);
        } catch ( \Exception $e ) {
            return $this->sendErrorResponse( 500, $e->getMessage());
        }
    }

    /**
     * 添加备注页
     *
     * @return View|string
     *
     * create by qgz 20190125
     */
    public function addRegisterNoteFormAction()
    {
        Assets::select2();
        Assets::importMainJs('assets/jquery/ajaxfileupload.js');
        Assets::easyUI('js/device/addRegisterNoteForm.js');
        $this->view->pick('device/addRegisterNoteForm');

        $device = $this->request->getQuery('device');
        $iUTId = $this->request->getQuery('iUTId');
        $devType = $this->request->getQuery('devType');
        try {
            if ($devType) {
                $proInfo = Ims::getProdInfoByName($devType);
                $accessory = $proInfo['mAccessory'] ? $proInfo['mAccessory'] : [];
            } else {
                $accessory = [];
            }
            return $this->view->setVars([
                'accessory' => $accessory,
                'device' => $device,
                'iUTId' => $iUTId
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 授权列表--添加备注
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190122
     * modify by dale 20190131  图片支持批量
     */
    public function addRegisterNoteAction()
    {
        $postData = $this->request->getPost();
        $imgArr = $this->request->getPost('imgArr');
        if (!$postData['device']) {
            return $this->sendErrorResponse(400, '请选择后操作');
        }
        if (!$postData['noteMag']) {
            return $this->sendErrorResponse(400, '请输入备注内容');
        }
        if ($postData['abnormal'] && !$imgArr) {
            return $this->sendErrorResponse(400, '异常时必须上传文件');
        }

        $dataArr = [];
        $this->db->begin();
        $commData = XhsysUsertabletNote::findFirst(['conditions' => 'bDelete = 0 and sDevNumber = :sDevNumber:', 'bind' => ['sDevNumber' => $postData['device']]]);
        if (!$commData) {
            $commData = new XhsysUsertabletNote;
            $commData->sDevNumber = $postData['device'];
        } else {
            if ($commData->sNoteMsg) {
                $dataArr = json_decode($commData->sNoteMsg, true);
            }
        }
        $dataArr[] = [
            'noteId' => $postData['device'] . $this->getRandStr(6),
//            'pen' => isset($postData['pen']) ? $postData['pen'] : '',//最初使用字段，已废弃
            'abnormal' => isset($postData['abnormal']) ? $postData['abnormal'] : 0,
            'accessory' => isset($postData['prodData']) && $postData['prodData'] ? $postData['prodData'] : '',
            'noteMag' => $postData['noteMag'],
            'imageUrl' => $imgArr ? implode(',', $imgArr) : '',
            'checkMsg' => [],
            'createId' => User::getId(),
            'createDate' => date('Y-m-d H:i:s')
        ];
        $commData->sNoteMsg = json_encode($dataArr, JSON_UNESCAPED_UNICODE);
        if (!$commData->save()) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '保存失败');
        }
        $findData = XhsysUsertablet::find(['conditions' => 'bDelete = 0 and sDevNumber = :sDevNumber:', 'bind' => ['sDevNumber' => $postData['device']]]);
        if ($findData) {
            foreach ($findData as $datum) {
                $datum->iCheck = 1;
                if (!$datum->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '修改审核状态失败');
                }
            }
        }
        $this->db->commit();
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 上传文件
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190122
     */
    public function uploadImageAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(500, '缺少文件');
        }
        $file = $this->request->getUploadedFiles()[0];
        if (!in_array(strtolower($file->getExtension()), ['jpg', 'jpeg', 'bmp', 'gif', 'png'])) {
            return $this->sendErrorResponse(400, '文件类型不正确');
        }
        $filePath = Main::getConfigByName('appParse');
        $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
        $fileName = $file->getName();
        $fullPath = $filePath . $fileName;
        if (!is_writable($filePath)) {
            return $this->sendErrorResponse(500, $filePath . '缓存无写入权限');
        }
        $file->moveTo($fullPath);
        $result = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
        @unlink($fullPath);
        if (!$result) {
            return $this->sendErrorResponse(500, '文件上传失败');
        } else {
            return $this->sendSuccessResponse($result);
        }
    }

    /**
     * 获取备注数据
     *
     * @return View|string
     *
     * create by qgz 20190122
     */
    public function getNoteMsgListAction()
    {
        $device = $this->request->getQuery('device');
        $iUTId = $this->request->getQuery('iUTId');
        $this->view->pick('device/registerNote');
        Assets::UEditor();
        Assets::easyUI('js/device/registerNote.js');
        if (!$device) {
            return $this->sendViewError('缺少设备号');
        }
        $data = XhsysUsertabletNote::findFirst([
            'columns' => 'sNoteMsg',
            'conditions' => ' bDelete = 0 and sDevNumber = :sDevNumber:',
            'bind' => ['sDevNumber' => $device]
        ]);
        if (!$data) {
            return $this->sendViewError('暂无记录');
        }
        if (!$data->sNoteMsg) {
            return $this->sendViewError('暂无记录');
        }
        $noteContent = json_decode($data->sNoteMsg, true);
        if ($noteContent) {
            foreach ($noteContent as &$value) {
                $value['abnormal'] = $value['abnormal'] ? '有异常' : '无异常';
                $value['createId'] = XhsysUser::getUserInfoById($value['createId'])['sUserName'];
                $value['date'] = date('m-d', strtotime($value['createDate']));
                $value['noteId'] = isset($value['noteId']) ? $value['noteId'] : '';
                if ($value['checkMsg']) {
                    foreach ($value['checkMsg'] as &$item) {
                        $item['createId'] = XhsysUser::getUserInfoById($item['createId'])['sUserName'];
                    }
                    unset($item);
                }
                if (!isset($value['accessory']) || !$value['accessory']) {//配件信息
                    $value['accessory'] = [];
                }
                if (isset($value['pen'])) {//pen是老字段，现在废弃，兼容以前数据
                    $value['pen'] = $value['pen'] ? '存在笔' : '不存在笔';
                } else {
                    $value['pen'] = '';
                }
                if ($value['imageUrl']) {
                    $value['imageUrl'] = explode(',', $value['imageUrl']);
                }
            }
            unset($value);
        }
        $power['check'] = Power::exist('Device_registerList_Check');
        return $this->view->setVars([
            'devName' => $device,
            'tabletId' => $iUTId,
            'data' => $noteContent,
            'power' => $power
        ]);
    }

    /**
     * 生成随机数
     *
     * @param $length
     *
     * @return string
     *
     * create by qgz 20190123
     */
    public function getRandStr($length){
        $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randStr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randStr .= $str[$num];
        }
        return $randStr;
    }

    /**
     * 添加审核数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190123
     */
    public function addRegisterCheckAction()
    {
        $postData = $this->request->getPost();
        if (!$postData['device']) {
            return $this->sendErrorResponse(400, '请选择后操作');
        }
        if (!$postData['noteId']) {
            return $this->sendErrorResponse(400, '缺少记录id');
        }
        if (!$postData['sContent']) {
            return $this->sendErrorResponse(400, '审核信息不能为空');
        }

        $this->db->begin();
        $findData = XhsysUsertabletNote::findFirst(['conditions' => 'bDelete = 0 and sDevNumber = :sDevNumber:', 'bind' => ['sDevNumber' => $postData['device']]]);
        if (!$findData || !$findData->sNoteMsg) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '未找到数据');
        }
        $dataArr = array_column(json_decode($findData->sNoteMsg, true), null, 'noteId');
        if (!isset($dataArr[$postData['noteId']])) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '未找到记录数据');
        }
        $dataArr[$postData['noteId']]['checkMsg'][] = [
            'checkDetail' => $postData['sContent'],
            'createId' => User::getId(),
            'createDate' => date('Y-m-d H:i:s')
        ];
        $findData->sNoteMsg = json_encode(array_values($dataArr), JSON_UNESCAPED_UNICODE);
        if (!$findData->save()) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '添加错误');
        }

        //检查是否全部审核完，是则修改授权表审核状态
        $allCheck = true;
        $checkArr = json_decode($findData->sNoteMsg, true);
        foreach ($checkArr as $final_datum) {
            if (empty($final_datum['checkMsg'])) {
                $allCheck = false;
            }
        }
        $updateData = XhsysUsertablet::find(['conditions' => 'bDelete = 0 and sDevNumber = :sDevNumber:', 'bind' => ['sDevNumber' => $postData['device']]]);
        if ($updateData) {
            foreach ($updateData as $datum) {
                $datum->iCheck = $allCheck ? 2 : 1;
                if (!$datum->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '修改审核状态失败');
                }
            }
        }
        $this->db->commit();
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 设备签收页
     *
     * @return View
     *
     * create by qgz 20190123
     */
    public function deviceSignInAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/device/deviceSignIn.js');
        if (!Power::exist('Device_SignIn')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        $signInEnum = ['' => '--状态--'] + $this->deviceSignIn;
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'device_signIn', 'style' => 'width: 90px;', 'data' => $signInEnum];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
        $listSearchArr[] = ['type'=>'button', 'id'=>'bt_list_search', 'text' => '查找', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        // $listButtonArr[] = ['id' => 'bt_list_changeStatus', 'text' => '修改状态', 'plain' => 'true', 'icon' => 'fa-pencil'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHSys_DeviceSignIn', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ]);
    }

    /**
     * 获取设备签收数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190123
     */
    public function getDeviceSignInAction()
    {
        $status = $this->request->getPost('status');
        $search = $this->request->getPost('search');
        $parameters = [
            'columns' => '*',
            'conditions' => ' bDelete = 0 ',
            'order' => 'tCreateDate DESC',
        ];
        if ($status !== '' && $status !== null) {
            $parameters['conditions'] .= ' and iStatus = :iStatus:';
            $parameters['bind'] = ['iStatus' => $status];
        }
        $otherParams = [];
        if ($search['vague']){//搜索人名和学校
            $userIdArr = User::searchUser($search['vague']);
            if (!empty($userIdArr)){
                $userIdArr = implode("','", $userIdArr);
                $otherParams = [" iUserId in ('" . $userIdArr . "')"];//OR的关系
            }
            $machId = School::searchSchool($search['vague']);
            if (!empty($machId)) {
                $machId = implode(',', $machId);
                $otherParams[] = " iSchoolId in ($machId) ";//OR的关系
            }
        }
        Main::runSearchVagueConditions($parameters['conditions'], ['sSignature', 'sLogonName', 'sAdClsName', 'sDeviceNumber', 'sIMei'], [], $otherParams);
        $data = Main::runModelPage('Admin\Models\device\XhsysDeviceSignIn', $parameters,
            ['iStatus' => $this->deviceSignIn, 'iSignInStatus' => $this->openStatus, 'iProtocolStatus' => $this->openStatus, 'iPartsStatus' => $this->openStatus]);
        Main::runUserNameById($data['rows'], ['iUserId'=>'sUserName'], true);
        Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
        foreach ($data['rows'] as &$value) {
            if ($value['sSignatureUrl']) {
                $value['sSignatureUrl'] = '<div><a style="cursor:pointer" imageUrl="'.$value['sSignatureUrl'].'" '.' class="image">点击查看</a></div>';
            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 修改签收状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190218
     */
    public function modifySignStatusAction()
    {
        $id = $this->request->getPost('id');
        $statusCode = $this->request->getPost('statusCode');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少参数id');
        }
        $data = XhsysDeviceSignIn::findFirst([
            'conditions' => 'bDelete = 0 and iId = :iId:',
            'bind' => ['iId' => $id]
        ]);
        if (!$data) {
            return $this->sendErrorResponse(500, '找不到数据');
        }
        $data->iStatus = $statusCode;
        if (!$data->save()) {
            return $this->sendErrorResponse(500, '修改出错');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 打印销售单
     *
     * @return View|string
     *
     * create by qgz 20190124
     */
    public function printReceiveDataAction()
    {
        Assets::easyUI('js/device/printReceiveForm.js');
        Assets::jQueryPrint();
        $this->view->pick('device/printReceiveForm');
        $id = $this->request->getQuery('id');
        if (!$id) {
            return $this->sendViewError('缺少参数');
        }
        $parameters = [
            'columns' => 'iRTId, iType, iStuNum, iCreateUserId, iSchoolId, iProdId, mTchBackInfo, mTchCode, mTabletShell',
            'conditions' => ' bDelete = 0 and iRTId = :iRTId:',
            'bind' => ['iRTId' => $id]
        ];
        try {
            $data = XHImsApplyTablet::findFirst($parameters);
            if (!$data) {
                return $this->sendViewError('暂无数据');
            } else {
                $data = [$data->toArray()];
            }
            Main::runUserName($data, ['iCreateUserId' => 'userName']);
            School::runName($data, ['iSchoolId' => 'schoolName']);
            $printer = [['printerId' => User::getId()]];
            Main::runUserName($printer, ['printerId' => 'printerName']);
            $printDate = date('Y-m-d');
            $data = $data[0];
            $printer = $printer[0];
            $staffInfoArr = Hrm::getStaffInfo([$data['iCreateUserId']]);
            $depName = $staffInfoArr[$data['iCreateUserId']]['depName'];
            $prodName = XHImsProduce::getProds();
            $data['mTchCode'] = $data['mTchCode'] ? unserialize($data['mTchCode']) : [];
            $data['mTchBackInfo'] = $data['mTchBackInfo'] ? unserialize($data['mTchBackInfo']) : [];
            $data['tabletShell'] = $data['mTabletShell'] ? unserialize($data['mTabletShell']) : [];
            $allNum = $allPrice = 0;
            $dataArr = [];
            if ($data['iProdId']) {
                $dataDetail = [
                    'id' => $data['iProdId'],
                    'name' => isset($prodName[$data['iProdId']]) ? $prodName[$data['iProdId']] :'',
                    'num' => $data['iStuNum'] ? $data['iStuNum'] : 0
                ];
                $proInfo = Ims::getProdInfoByName($dataDetail['name']);
                $dataDetail['measure'] = $proInfo['sMeasure'];
                $dataDetail['price'] = number_format($proInfo['dOutPrice'], 2);
                $dataDetail['allPrice'] = number_format($proInfo['dOutPrice'] * $dataDetail['num'], 2);
                $dataDetail['model'] = '';
                $dataArr[] = $dataDetail;
                $allNum += $dataDetail['num'];
                $allPrice += $proInfo['dOutPrice'] * $dataDetail['num'];
            }
            if ($data['mTchBackInfo']) { //有教师直接入库信息
                foreach ($data['mTchBackInfo'] as $prodDetail) {
                    $dataDetail = [
                        'id' => $prodDetail['prodId'],
                        'name' => isset($prodName[$prodDetail['prodId']]) ? $prodName[$prodDetail['prodId']] :'',
                        'num' => $prodDetail['prodNum'] ? $prodDetail['prodNum'] : 0
                    ];
                    $proInfo = Ims::getProdInfoByName($prodName[$prodDetail['prodId']]);
                    $dataDetail['measure'] = $proInfo['sMeasure'];
                    $dataDetail['price'] = number_format($proInfo['dOutPrice'], 2);
                    $dataDetail['allPrice'] = number_format($proInfo['dOutPrice'] * $dataDetail['num'], 2);
                    $dataDetail['model'] = '';
                    $dataArr[] = $dataDetail;
                    $allNum += $dataDetail['num'];
                    $allPrice += $proInfo['dOutPrice'] * $dataDetail['num'];
                }
            } else if ($data['mTchCode']) {
                $newMergeArr = [];
                foreach ($data['mTchCode'] as $detail) {
                    $newMergeArr[$detail['iProdId']][] = $detail;
                }
                foreach ($newMergeArr as $prodId => $prodDetail) {
                    $dataDetail = [
                        'id' => $prodId,
                        'name' => isset($prodName[$prodId]) ? $prodName[$prodId] :'',
                        'num' => count($prodDetail)
                    ];
                    $proInfo = Ims::getProdInfoByName($prodName[$prodId]);
                    $dataDetail['measure'] = $proInfo['sMeasure'];
                    $dataDetail['price'] = number_format($proInfo['dOutPrice'], 2);
                    $dataDetail['allPrice'] = number_format($proInfo['dOutPrice'] * count($prodDetail), 2);
                    $dataDetail['model'] = '';
                    $dataArr[] = $dataDetail;
                    $allNum += $dataDetail['num'];
                    $allPrice += $proInfo['dOutPrice'] * count($prodDetail);
                }
            }
            if ($data['tabletShell']) {
                if (is_array($data['tabletShell'])) {
                    foreach ($data['tabletShell'] as $key => $value){
                        $dataDetail = [
                            'id' => $value['prodId'],
                            'name' => isset($prodName[$value['prodId']]) ? $prodName[$value['prodId']] :'',
                            'num' => $value['iNum'] ? $value['iNum'] : 0
                        ];
                        $proInfo = Ims::getProdInfoByName($prodName[$value['prodId']]);
                        $dataDetail['measure'] = $proInfo['sMeasure'];
                        $dataDetail['price'] = number_format($proInfo['dOutPrice'], 2);
                        $dataDetail['allPrice'] = number_format($proInfo['dOutPrice'] * $dataDetail['num'], 2);
                        $dataDetail['model'] = '';
                        $dataArr[] = $dataDetail;
                        $allNum += $dataDetail['num'];
                        $allPrice += $proInfo['dOutPrice'] * $dataDetail['num'];
                    }
                }
            }
            if ($dataArr) {
                $dataArr[] = ['id' => '合计', 'name' => '', 'num' => $allNum, 'measure' => '', 'price' => '', 'allPrice' => number_format($allPrice, 2), 'model' => ''];
            }
            return $this->view->setVars([
                'date' => $printDate,
                'userName' => $data['iCreateUserId'] ? $data['userName'] : '(无)',
                'depName' => $depName,
                'printer' => $printer['printerName'],
                'school' => $data['schoolName'],
                'printId' => 'I0-' . date('Y-m') . '-' . substr(time(), -6),
                'data' => $dataArr
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 填写设备变更信息页
     *
     * @return View|string
     *
     * create by qgz 20190221
     */
    public function exchangeDeviceAction()
    {
        if (!Power::exist('Device_Exchange_Add')) {
            return $this->sendViewError('没权限查看此页');
        }
        $this->view->pick('device/exchangeDeviceForm');
        Assets::select2();
        Assets::easyUI('js/device/exchangeDevice.js');
        return $this->view->setVars([]);
    }

    /**
     * 保存设备授权申请变更数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190221
     */
    public function saveExchangeDeviceAction()
    {
        $id = $this->request->getPost('id');
        $deviceType = $this->request->getPost('deviceType');
        $teacher = $this->request->getPost('teacher');
        $school = $this->request->getPost('school');
        if (!$id || !in_array($deviceType, [0, 1, 2, 3])) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        $findData = XhsysUsertablet::findFirst([
            'conditions' => 'iUTId = :iUTId:',
            'bind' => ['iUTId' => $id]
        ]);
        if (!$findData) {
            return $this->sendErrorResponse(500, '找不到授权数据');
        } else {
            $findData = $findData->toArray();
        }
        $name = XhsysUser::findFirst([
            'columns' => 'sUserName, sLogonName',
            'conditions' => 'iUserId = :iUserId:',
            'bind' => ['iUserId' => $teacher]
        ]);
        $addData = [
            'iUTId' => $findData['iUTId'],
            'sDevNumber' => $findData['sDevNumber'],
            'sDevType' => $findData['sDevType'],
            'iReceiverId' => $teacher ? $teacher : '',
            'sReceiver' => $name ? $name->sUserName : '',
            'sReceiverAccount' => $name ? $name->sLogonName : '',
            'iNewPurpose' => $deviceType,
            'iPurpose' => $findData['iReceivePurpose'],
            'iSchoolId' => $school ? $school : '',
            'iOldSchoolId' => $findData['iSchoolId']
        ];
        $newPro = new XhsysTabletExchange();
        $newPro->assign($addData);
        if (!$newPro->save()) {
            return $this->sendErrorResponse(500, '保存失败');
        }
        return $this->sendSuccessResponse('申请成功，请等待审核');
    }

    /**
     * 获取所有学校列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190223
     */
    public function getAllSchoolAction()
    {
        $return[] = ['id' => '', 'text' => ''];
        $allSchool = School::getSchools();
        foreach ($allSchool as $key => $value) {
            $return[] = ['id' => $key, 'text' => $value];
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 获取该学校下的教师数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190223
     */
    public function getTchBySchoolAction()
    {
        $school = $this->request->getPost('school');
        $return[] = ['id' => '', 'text' => ''];
        $allTch = School::getTchBySchoolId($school, true);
        foreach ($allTch as $key => $value) {
            $return[] = ['id' => $key, 'text' => $value];
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 设备变更申请页
     *
     * @return View
     *
     * create by qgz 20190221
     */
    public function deviceExchangeAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/device/deviceExchange.js');
        if (!Power::exist('Device_Exchange')) {
            return $this->sendViewError('无查看此页面权限');
        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_applyStatus', 'style' => 'width:60px;',
                            'data' => ['' => '-审核-'] + [0 => '未审核', 1 => '通过', 2 => '不通过']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_financeStatus', 'style' => 'width:90px;', 'label' =>'  ',
                            'data' => ['' => '-财务审核-'] + [0 => '未审核', 1 => '通过', 2 => '不通过']];
        $listSearchArr[] = ['label' =>'  搜索：', 'type' => 'text', 'id' => 'list_vague'];
        if (Power::exist('Device_Exchange_ApplyCheck')) {
            $listButtonArr[] = ['id' => 'bt_list_check', 'text' => '审核', 'plain' => 'true', 'icon' => 'fa-check'];
        }
        if (Power::exist('Device_Exchange_FinaCheck')) {
            $listButtonArr[] = ['id' => 'bt_list_financeCheck', 'text' => '财务审核', 'plain' => 'true', 'icon' => 'fa-check-square-o'];
        }
        return $this->view->setVars([
            'List'          => Template::createList('list', 'XHSys_DeviceExchange', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取设备变更申请数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by qgz 20190221
     */
    public function getExchangeDeviceAction()
    {
        $applyStatus = $this->request->getPost('applyStatus');
        $financeStatus = $this->request->getPost('financeStatus');
        $params = [
            'conditions' => 'bDelete = 0 ',
            'order'      => 'iUTId desc'
        ];
        if (true) {
//            $staff = XhhrmStaff::findFirst([
//                'conditions' => 'bDelete = 0 AND iUserId = :userId:',
//                'bind'       => ['userId' => User::getId()]
//            ])->iUserId;
//            if (!$staff) {
//                return $this->sendDataGridError('非员工无法查询');
//            }
            $schoolPowerIds = School::getPower();
            if (!$schoolPowerIds) {
                $params['conditions'] .= ' AND (iReceiverId = :iReceiverId: OR iCreateUserId = :iCreateUserId:) ';
                $params['bind']['iReceiverId'] = User::getId();
                $params['bind']['iCreateUserId'] = User::getId();
            }
            else if ($schoolPowerIds !== true) {
                $params['conditions'] .= ' AND (iReceiverId = :iReceiverId: OR iCreateUserId = :iCreateUserId: OR iSchoolId in ({schoolPowerIds:array}) OR iOldSchoolId in ({oldSchoolPowerIds:array})) ';
                $params['bind']['iReceiverId'] = User::getId();
                $params['bind']['iCreateUserId'] = User::getId();
                $params['bind']['schoolPowerIds'] = $schoolPowerIds;
                $params['bind']['oldSchoolPowerIds'] = $schoolPowerIds;
            }
        }
        if ($applyStatus !== null && $applyStatus !== '' && in_array($applyStatus, [0, 1, 2])) {
            $params['conditions'] .= ' and iCheckStatus = :iCheckStatus: ';
            $params['bind']['iCheckStatus'] = $applyStatus;
        }
        if ($financeStatus !== null && $financeStatus !== '' && in_array($financeStatus, [0, 1, 2])) {
            $params['conditions'] .= ' and iFinanceStatus = :iFinanceStatus: ';
            $params['bind']['iFinanceStatus'] = $financeStatus;
        }
        $enum['iPurpose'] = $enum['iNewPurpose'] = $this->registerEnum['iReceivePurpose'];
        $enum['iCheckStatus'] = $enum['iFinanceStatus'] = [
            0 => '未审核',
            1 => '通过',
            2 => '不通过'
        ];
        Main::runSearchVagueConditions($params['conditions'], ['sCheckUser', 'sFinanceCheck', 'sDevNumber', 'sDevType', 'sReceiver', 'sReceiverAccount']);
        $data = Main::runModelPage('\\Admin\\Models\\device\\XhsysTabletExchange', $params, $enum);
        Main::runUserName($data['rows'], ['iLastModifyUserId' => 'iLastModifyUserId', 'sCheckUser' => 'sCheckUser', 'sFinanceCheck' => 'sFinanceCheck', 'iCreateUserId' => 'iCreateUserId']);
        School::runName($data['rows'], ['iSchoolId' => 'sSchoolName', 'iOldSchoolId' => 'sOldSchoolName']);
        foreach ($data['rows'] as &$value) {
            $color1 = $value['iCheckStatus'] == '未审核' ? 'gray' : ($value['iCheckStatus'] == '通过' ? 'green' : 'red');
            $color2 = $value['iFinanceStatus'] == '未审核' ? 'gray' : ($value['iFinanceStatus'] == '通过' ? 'green' : 'red');
            $value['iCheckStatusStr'] = $value['sCheckUser'] ?
                '<div class="grid-cell-text-bg-' . $color1 . '">' . $value['iCheckStatus'] . '【' . $value['sCheckUser'] . $value['sCheckDate'] . '】' . '</div>' :
                '<div class="grid-cell-text-bg-' . $color1 . '">' . $value['iCheckStatus'] . '</div>';
            $value['iFinanceStatusStr'] = $value['sFinanceCheck'] ?
                '<div class="grid-cell-text-bg-' . $color2 . '">' . $value['iFinanceStatus'] . '【' . $value['sFinanceCheck'] . $value['sFinanceCheckDate'] . '】' . '</div>' :
                '<div class="grid-cell-text-bg-' . $color2 . '">' . $value['iFinanceStatus'] . '</div>';
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 修改设备变更申请状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190221
     */
    public function saveExchangeStatusAction()
    {
        $idArr = $this->request->getPost('ids');
        $status = $this->request->getPost('status');
        $type = $this->request->getPost('type');
        if (!$idArr || !$status || !$type) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $data = XhsysTabletExchange::find([
            'conditions' => " bDelete = 0 and iId in ({idArr:array}) ",
            'bind' => ['idArr' => $idArr]
        ]);
        if (!$data) {
            return $this->sendErrorResponse(500, '找不到数据');
        }
        foreach ($data as $datum) {
            if ($type == 1) {//申请审核
                $datum->iCheckStatus = $status;
                $datum->sCheckUser = User::getId();
                $datum->sCheckDate = date('Y-m-d H:i:s');
            } else {//财务审核
                $datum->iFinanceStatus = $status;
                $datum->sFinanceCheck = User::getId();
                $datum->sFinanceCheckDate = date('Y-m-d H:i:s');
                if ($status == 1) {//审核通过
                    //将授权表原数据置为历史，新建一条授权记录
                    $tabletData = XhsysUsertablet::findFirst([
                        'conditions' => 'bHistory = 0 and iUTId = :iUTId: ',
                        'bind' => ['iUTId' => $datum->iUTId]
                    ]);
                    if ($tabletData) {
                        $newPro = new XhsysUsertablet();
                        $receiverInfo = XhsysUser::getUserInfoById($datum->iCreateUserId);
                        $newPro->sReceiverName = $receiverInfo['sUserName'];
                        $newPro->sReceiverAccount = $receiverInfo['sLogonName'];
                        $newPro->sReceiverPhone = $receiverInfo['sSelfPhone'];
                        $newPro->iReceivePurpose = $datum->iNewPurpose;
                        $newPro->tReceiveTime = date('Y-m-d H:i:s');
                        $newPro->sDevNumber = $datum->sDevNumber;
                        if ($datum->iReceiverId) {//计新的具体数据，前身具体数据不计表，仅计老的id
                            $newPro->iNowReceiverId = $datum->iReceiverId;
                            $newPro->sNowReceiverName = $datum->sReceiver;
                            $newPro->sNowReceiverAccount = $datum->sReceiverAccount;
                            $newPro->tNowReceiveTime = date('Y-m-d H:i:s');
                        }
                        $newPro->iSource = 2;
                        $newPro->sDevType = $datum->sDevType;
                        $newPro->iSchoolId = $datum->iSchoolId;
                        $newPro->iBeforeUTId = $datum->iUTId;//前身id
                        if (!$newPro->save()) {
                            return $this->sendErrorResponse(500, '保存出错');
                        }
                        $tabletData->iNewUTId = $newPro->iUTId;//后世id
                        $tabletData->sNewReceiver = $datum->iCreateUserId;
                        $tabletData->iNewPurpose = $datum->iNewPurpose;
                        $tabletData->sNewNowReceiver = $datum->iReceiverId;
                        $tabletData->bHistory = 1;
                        if (!$tabletData->save()) {
                            return $this->sendErrorResponse(500, '保存授权表出错，id:' . $tabletData->iUTId);
                        }
                    }
                }
            }
            if (!$datum->save()) {
                return $this->sendErrorResponse(500, '新增授权表出错，申请id:' . $datum->iUTId);
            }
        }
        return $this->sendSuccessResponse('成功');
    }

}

